[Date Prev][Date Next][Thread Prev][Thread Next]
- Subject: Multiple return value in __index metamethod
- From: Lavergne Thomas <thomas.lavergne@...>
- Date: Tue, 10 Jul 2007 19:31:39 +0200
The program I currently write with Lua and C use a lot of objects with
an __index metamethod. And today I've wanted to extend one of these
objects and return more information from one of theses __index. The
frist thing that come to my mind was to use the lua ability to return
multiple values from functions. This have the advantage of keeping
compatibility (with checking for some special case) and nearly no
overhead for the existing code.
But in metamethods (except for __call) the number of return values is
adjusted to 1.
I easily understand why in case of metamethod like __add or like but is
there any reason to do this for __index ?
I think the documentation is false for this. In lua code for __index the
return value is :
return h(table, key)
and for __call :
return h(func, ...)
So the same call. I've assumed that in both case, all the result were
returned. The return for __index and like must be written :
return (h(table, key))
so the adjustement is clear.
But why adjusting ? I've think about it, and if I admit that it could
seems confusing to return more than 1 value when indexing a table, it's
not so surpinsing in a language like lua where function can return
multiples values. Is there a technical reason I've not seen ?
In my case I have different possibility do handle this. I can make my
__index methods return a table of these values, but this have the
ovrhead to create a lot of very small tables destroyed almost imediatly
and so trigger the gc a lot more often, and I must modify all the
Or I can use a classical method in my object returning this second value
leading to a less natural and less elegant lua code. And also less
efficient cause the two values result for the same computation, so it
will be calculated two times.
Can I hope for allowing multiples return value in __index in a next
version of lua ?
PS: I'm very sorry for my bad english.
Thomas Lavergne "Le vrai rêveur est celui qui rêve
de l'impossible." (Elsa Triolet)