lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


Wrap the function as the __call metamethod in a table?

On 8/3/07, PA <petite.abeille@gmail.com> wrote:
> Hello,
>
> For the record:
>
> % lua -v
> Lua 5.1.2  Copyright (C) 1994-2007 Lua.org, PUC-Rio
>
> With setmetatable, one can assign a metatable per table instance. One
> the other hand, debug.setmetatable seems to assign a metatable per
> object type, not object instance, e.g.:
>
> local aFunction = function() end
>
> debug.setmetatable( aFunction, { __len = function() return 1 end } )
>
> print( #aFunction )
>
>  >       1
>
> Unfortunately, it seems like all function instances share the same
> metatable:
>
> local anotherFunction = function() end
>
> debug.setmetatable( anotherFunction, { __len = function() return 2 end
> } )
>
> print( #aFunction, #anotherFunction )
>
>  >       2       2
>
> This even though the documentation states that debug.setmetatable is
> "for the given object", not object type:
>
> "Sets the metatable for the given object to the given table (which can
> be nil)."
>
> Bug or feature?
>
> In any case, how to get around such conundrum and properly simulate one
> metatable per function instance?
>
> Perhaps one could try using a function environment, which can be set
> per function instance:
>
> local aFunction = function() end
>
> debug.setmetatable( aFunction, { __len = function( self ) return
> getfenv( self ):__len() end } )
>
> setfenv( aFunction, { __len = function() return 1 end } )
>
> local anotherFunction = function() end
>
> setfenv( anotherFunction, { __len = function() return 2 end } )
>
> print( #aFunction, #anotherFunction )
>
>  >       1       2
>
> Is there a more straightforward way?
>
> Thanks in advance.
>
> Cheers,
>
> PA.
>
>