[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: __call?
- From: Spencer Schumann <gaucho_puro@...>
- Date: Fri, 12 Dec 2003 06:29:09 -0800 (PST)
The __call metamethod allows a table to be used as a function. This is similar to C++'s operator
() for overloading the function call operator on objects.
Example using __call:
local mt =
{
__call = function(t, quote)
print(t.name .. " says, \"" .. quote .. "\"")
end
}
function makeperson(name)
local t = {name = name}
setmetatable(t, mt)
return t
end
local bart = makeperson("Bart Simpson")
bart("I didn't do it!")
The __call metamethod is passed the table used as a first argument, which allows the metamethod to
access the table that was used in performing the function call.
Of course, for this example, closures can be used for the same purpose.
Example using Closures:
function makeperson2(name)
return function(quote)
print(name .. " says, \"" .. quote .. "\"")
end
end
local ralph = makeperson2("Ralph Wiggam")
ralph("Daddy says I'm this close to sleeping in the yard.")
The method of using __call would allow for other metamethods to also be used on a given object,
hich can make it more flexible than just using closures.
As far as distinguishing between obj:Method() and obj.Method(), are you trying to determine
whether the method was called improperly without using the method call syntax? If so, it seems
that you just need to check that the first argument is a valid table.
--- Ando Sonenblick <ando@spritec.com> wrote:
> Gang,
>
> Thanks to all for help with my lua question about auto initing nil
> values in a table to zero...
>
> A couple replies utilize the __call metamethod. I'm not terribly
> familiar with this one and the manual only has this to say about it:
>
> ? "call": called when Lua calls a value.
> function function_event (func, ...)
> if type(func) == "function" then
> return func(unpack(arg)) -- primitive call
> else
> local h = metatable(func).__call
> if h then
> return h(func, unpack(arg))
> else
> error("...")
> end
> end
> end
>
>
> Can anyone give me more info on this? What exactly does it mean when
> "Lua calls a value"?
>
> Can I use this to distinguish between obj:Method() and obj.method?
>
> Thanks for any insight...
>
> Ando
> -----------------------
> Ando Sonenblick
> SpriTec Software
> www.spritec.com
__________________________________
Do you Yahoo!?
New Yahoo! Photos - easier uploading and sharing.
http://photos.yahoo.com/