Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
1

Why is self the class itself?

Asked by 2 years ago

I am a fairly new person to OOP and I am confused by this code.

local module = {}
module.__index = module

function module:new()
    print(self)
    local o = setmetatable({}, self) 


    return o
end

function module:Method()
    print(self)
end

return module

----------server script--------------

local module = require(game.ReplicatedStorage:WaitForChild("moduleScripts").testClass)

local t = module:new()


print(t)
t:Method()

The print on line 5 prints the actual module. But shouldn't it print an empty table because self returns the table that is calling it which would be t?

The method on line 13 prints the empty table, T, so that confuses me even further.

The reason I think that it should print the empty table T is because using colons to call methods defines self as the table the method is acting on. So shouldn't self be t?

I think I have a good understanding of metatables, so unless my understanding of it is wrong you don't have to explain it.

1 answer

Log in to vote
1
Answered by
Speedmask 661 Moderation Voter
2 years ago
Edited 2 years ago

shouldn't it print an empty table because self returns the table that is calling it which would be t?

indeed. and you’re not calling from t. you’re calling module:new() which means self is the module. however, t:Method() is. whatever comes before the colon is what self is.

I would assume that’s why many people use .new() rather than :new(), although it really doesn’t matter. to prevent confusion, I always do this at the top of my constructor:

local obj = {}
obj.__index = obj

-- using dot new
function obj.new()
    local self = setmetatable({}, obj)
    self.blah = 5
    return self
end

-- using colon new
function obj:new()
    self = setmetatable({}, self)
    self.blah = 5
    return self
end

now self refers to the actual table either way you slice it.

0
Thank you! movementkeys 163 — 2y
Ad

Answer this question