local module = require(script.Test)
local new = module.new()
new:Start()
the module :
local module = {}
module.__index = module
local dochat = require(script.DoChat)
local system = require(script.System)
function module.new()
local t = {}
local event = Instance.new("BindableEvent")
t.onmsg = event.Event
t.__onmsg = event
return setmetatable(t,module)
end
function module:Chat(Message)
self.__onmsg:Fire(Message)
dochat.Chat(Message)
end
function module:Start()
local t = self
setmetatable(t,module)
print(t)
end
return module
So, at the start function when i try to print self(the setmetatable(t,module))
it doesnt print the functions so i just see the variables that i set at the .new function.
how do i fix this? if theres no solution for it how can i make it (i wanna make the system module use the :chat function)
It already pointed t (self), to the module. Therefore, if you call :Chat on the returned object, and the code doesn’t find the function in the object, it’s going to look into the module.
When you print self, it indeed prints whatever the returned object contains. However, if you print getmetatable(self), you’re going to see everything else.
Setting another metatable in the :Start() function isn’t necessary.
function module:Start()
local t = self
setmetatable(t,module)
print(t)
end
Is completely useless, you’re already attaching a metatable within the constructor (the .new() function) so no need to do it again.
To answer your question, “t” doesn’t contain actually contain any of the functions, so you wouldn’t see any of them when you print the table out. Instead, it has a metatable attached to it that contains all of the functions that also contains the .__index metamethod. (Like @waves5217 said you can use getmetatable(self) to see the functions)
When you call a function within your object, Lua will first look for the function inside of the “t” table, if it find it, it calls it. If it doesn’t find it, it’ll check if the “t” table has a metatable attached to it, it does, it sees that the metatable contains the .__index metamethod and will then search the metatable for the function, if it finds it inside of the metatable, it’ll call it.
You don’t need to reset the meta table in the Start function.
local module = {}
module.__index = module
local dochat = require(script.DoChat)
local system = require(script.System)
function module.new()
local t = {}
local event = Instance.new("BindableEvent")
t.onmsg = event.Event
t.__onmsg = event
return setmetatable(t,module)
end
function module:Chat(Message)
self.__onmsg:Fire(Message)
dochat.Chat(Message)
end
function module:Start()
-- Can now use self to access the current object. i.e:
self.onmsg
self.__onmsg
self:Chat("Message Here")
end
return module