lua-users home
lua-l archive

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


In fact it could as well be iumplemented as syntaxic sugar:
  t[1,2] being equivalent to t[1][2] (i.e. using tables of tables)
But what you propose is to extend the keys using table values, i.e.
  t[t.tuple(1,2)]
using a tuple(a,b) function as a member of table t (alternatively as a metatable member where __index would resolve "tuple" to a function creating a table entry in getmetable(t).tuples or computing an integer index from (a,b) if (a,b) are integers whose range is known in (1..N, 1..P), because in that case that tuple(a,b) function would just return (a*P+b) without needing an extra table for the unique keys.

Yes there are multiple ways to do that, it all depends on how indexes are composed to create a unique key: an integer or a table of tuples.

If syntaxic sugger is just  t[1,2] being equivalent to t[1][2], there's no real need of it, it just saves one character in the source (except that it is implied that t[1] will be allocated a new table automatically if it is still nil, so that t[1][2] becomes usable without raising an error (attempt to index a nil object which is not a table).

The alternative would be possible however by accepting t[1,2] if t has a metatable containing a __tuple constructor, returning a single key of any type (it does not matter where the tuple will be stored, either as an table in an table of unique tuples, or as a single integer.

Programmers have the choice and in fact different factores may decide them. So I don't clearly see why Lua would require a single choice.

If there's someting to do in Lua, in my opinion it should allow "t[1][2] = value" so that t[1] will be implicitly assigned a new table if it's still nil (the compiler automatically inserting the test and creation of a new table in t[1] where needed. As this can be costly and repetitive in may cases where tables are used this is where the syntax t[1,2] would be the most productive (but still as syntaxic sugar which can be written in Lua)


Le dim. 9 déc. 2018 à 19:12, Dirk Laurie <dirk.laurie@gmail.com> a écrit :
There are many ways to implement multi-indexed tables in Lua, but
since that is not the main point of the post, I'll just pick one,
namely to wrap the indices into a tuple as described for example in
these articles on the Lua wiki:

http://lua-users.org/wiki/SimpleTuples
http://lua-users.org/wiki/FunctionalTuple

In either case, you code something like tbl[tuple(1,2)] where you
would have liked to code tbl[1,2]. And you can obviously monkey-patch
rawget and rawset to accept more arguments.

Now the real questions:

1. Is there any syntactic reason why one can't patch Lua so that
t[1,2] won't raise a compilation error, but instead invoke
__index(t,1,2) or __newindex(t,1,2,v)?
2. Has anyone done it already?