• Why is the function within my metatable automatically being called?
    6 replies, posted
From what I can recall from my Lua days prior to Garry's Mod, the [i]__call[/i] metamethod would never be called upon until you specifically call your table. However, using [code]for k,v in ipairs(nodes) do local meta = { __call = Print() } setmetatable(nodes[k], meta) end[/code] the [i]Print()[/i] function automatically gets called (and obviously prints a message) for every single table within the table. Note that [i]Print()[/i] is merely a placeholder function in an attempt to figure this out. What's going on? Am I missing something here?
What you're actually doing, is setting __call to whatever Print() returns, so Print() gets called. You probably want something like [lua] for k,v in ipairs(nodes) do local meta = { __call = function () Print("Hi!") end } setmetatable(nodes[k], meta) end [/lua]
So is there no way whatsoever to assign seperate functions to each individual table?
[QUOTE=WickeTD;40700229]So is there no way whatsoever to assign seperate functions to each individual table?[/QUOTE] What you want is to have Print() return a function. Something like: [lua]function Print(...) return function() print("test: ", ...) end end[/lua]
[QUOTE=thejjokerr;40700566]Or just __call = Print Without the parentesis[/QUOTE] This wouldn't allow it to be different for every table that inherits it.
__call gets passed the table as the first argument (similar to calling tab:__call), so based on that you don't really need to define a new function every time you create the inheritance.
Sorry, you need to Log In to post a reply to this thread.