lua-users home
lua-l archive

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


On Wed, Dec 15, 2010 at 6:59 AM, steve donovan
<steve.j.donovan@gmail.com> wrote:
> It is consistent then to see the table.* functions as working only on
> raw tables, and thus generally not respecting your attempts at
> virtualisation.
>
> Consider table.insert - even if your table has a __setindex to enforce
> what goes into it, this function will ignore that. This is one big
> difference between table.insert(t,val) and t[#t+1] = val. (This came
> up when I was constructing a 'safe' array that could guarantee no
> holes would be inserted..)

Well, such kind of table virtualization was out of the question in Lua
5.1; the table module had no way to know the length of the virtual
table, and without the length, no table operation made sense. However,
in Lua 5.2, this is no longer the case because __len is honored on
tables. The table module could be made to use lua_gettable and
lua_settable instead of lua_rawgeti and lua_rawseti.

This change is easy to make in ltablib.c, and it opens up very
intersting possibilities such as table virtualization, or table
operations on any userdata that has __len, __index and __newindex
metamethods. You could make a userdata that wraps a C array, and use
table.sort(), table.concat() or table.unpack() on it.

Besides, the manual gives the impression that the functions in the
table module already honor the __index metamethod.

For example, the table.concat documentation says:

"Given an array where all elements are strings or numbers, returns
table[i]..sep..table[i+1] ··· sep..table[j]"

For the current implementation, this should be changed to:

"Given an array where all elements are strings or numbers, returns
rawget(table, i)..sep..rawget(table, i+1) ··· sep..rawget(table, j)"

We see similar examples in the table.unpack and table.sort documentation.

- Keith