lua-users home
lua-l archive

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


On Mon, May 18, 2009 at 5:46 PM, steve donovan
<steve.j.donovan@gmail.com> wrote:
> Hi guys,
>
> Any Lua type can have a metatable (apart from userdata and tables) but
> it applies to every instance of that type. This is very useful (e.g.
> allowing things like s:sub(1,-2)) but sometimes it would be very
> _cool_ if individual functions could have their own metatable.  It
> would make for a more polymorphic way of doing things. For instance,
> in PL the functions creating sequences return functions, so that they
> are immediately consumable by for loops, etc.  To chain methods
> operating on sequences, it's necessary to create a wrapper object
> explicitly.  Now this wrapper object defines __call appropriately, so
> the result is still callable ('functors'). This tends to be the
> recommended practice, but one takes a performance hit for this.
>
> Metatables for individual functions would allow method chains
> operating on functions. So the question is, what are the performance
> implications of such a feature?
>
> steve d.
>

Another way I think it could be useful is where you need to "tag"
certain functions - for example, say you have an __index metamethod
that looks up the key in a hidden table containing both ordinary
method functions, and "property-getter" functions - the former should
be returned normally, but the latter should immediately be called,
passing in "self" as a parameter. A metatable would let you quickly
tell what kind of function you have and take the right course of
action. (Two tables is the obvious solution for achieving this right
now, but it obviously requires an extra table lookup, at least some of
the time.)

-Duncan