lua-users home
lua-l archive

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


Jerome Vuarand <jerome.vuarand <at> ubisoft.com> writes:
> Another solution that no one else proposed is to pass several keys to
> your __index metamethods. You can do that by creating a table

The following variant of that approach avoids constructing a table and is
reasonably straightforward and efficient:

  value, delta = t[i], t[-i]

(assuming the key i is a positive integer so that the domains of i
and -i are mutually exclusive).

I also like the common solution:

  value, delta = t:pair(i)    -- just get used to it ;)

Now, if we did allow __index to return multiple values, then someone
might ask why __newindex doesn't accept multiple values (for setting
both values atomically):

  t[i] = value, delta

Without syntactic changes, that doesn't work in Lua because it will be
interpreted as "t[i] = value".  A common solution is

  t:pair(i, value, delta)  -- set