{ __call = Class.new } produces closure?

General discussion about LÖVE, Lua, game development, puns, and unicorns.
Post Reply
User avatar
raidho36
Party member
Posts: 2063
Joined: Mon Jun 17, 2013 12:00 pm

{ __call = Class.new } produces closure?

Post 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.
User avatar
Inny
Party member
Posts: 652
Joined: Fri Jan 30, 2009 3:41 am
Location: New York

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

Post 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 }
User avatar
raidho36
Party member
Posts: 2063
Joined: Mon Jun 17, 2013 12:00 pm

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

Post 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.
Post Reply

Who is online

Users browsing this forum: rabbitboots and 234 guests