Page 1 of 1

{ __call = Class.new } produces closure?

Posted: Thu Sep 01, 2016 4:38 am
by raidho36
I'm not exactly concerned with this, I just don't quite understand how that works. Can anyone explain why setting a class metatable like this results in closures, most notably replacing passed argument tables with duplicates, which aren't even complete duplicates for some reason? I've also tried defining a local function but that didn't helped. It does work as expected if you simply call the function directly.

Re: { __call = Class.new } produces closure?

Posted: Thu Sep 01, 2016 4:47 am
by Inny
In the Lua reference manual, the __call metamethod is defined with this code:

Code: Select all

function function_event (func, ...)
   if type(func) == "function" then
     return func(...)   -- primitive call
   else
     local h = metatable(func).__call
     if h then
       return h(func, ...)
     else
       error(···)
     end
   end
 end
the part where h(func, ...) is called, what they mean is the table being called, it gets passed as the first argument. It's not a duplicate, it's an alias.

In your example, what you really are intending to do is this:

Code: Select all

{ __call = function(class, ...) return class.new(...) end }

Re: { __call = Class.new } produces closure?

Posted: Thu Sep 01, 2016 5:01 am
by raidho36
Thank you! I seem to got the wrong impression from the behavior since the function argument was another class table, and I expected that it would go into the first argument.