[Date Prev][Date Next][Thread Prev][Thread Next]
- Subject: Re: Multiple return value in __index metamethod
- From: Rici Lake <lua@...>
- Date: Tue, 10 Jul 2007 12:54:37 -0500
On 10-Jul-07, at 12:31 PM, Lavergne Thomas wrote:
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 ?
__index is triggered by the use of an index operation in Lua, including
t, t.foo, t:meth()
Like the arithmetic operators, these operations are adjusted to
a single value; in the compiled VM code, they compile to a single
operation. Allowing multiple returns would be a complication to
the VM design, and would likely be considerable overhead for a
fairly rare use case.
I think the documentation is false for this. In lua code for __index
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
The number of return values consumed is determined by the caller,
not the function called. So the description is technically correct.
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
Why not just use classic accessor functions? That is:
It seems easier than the other possibilities, and has the advantage
of working :)