lua-users home
lua-l archive

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


On Wed, Jul 08, 2015 at 11:36:47PM +0200, Philipp Janda wrote:
> Am 08.07.2015 um 19:52 schröbte Andrew Starks:
> >
> >Lua strings are tuples, correct?
> >
> 
> I'd say: Tuples are to tables what strings are to userdata.
> 
> Have you ever wondered why strings aren't implemented as userdata (given
> Lua's minimalistic nature)? Both are essentially sequences of bytes, after
> all.
> 

By using the term, tuple, in such an abstract manner it basically loses all
practical meaning. Everything is a tuple. Numeric values are treated just
like string values in Lua, too. Numeric values are 1-tuples. Strings (both
in the abstract and in the Lua implementation) are either n-tuples or
1-tuples, depending on context. Userdata are 1-tuples just like numbers,
with the only difference being that the values come from a different domain.

What are we to make of these equivalencies, though?

Ultimately the OP simply wanted to be able to index a data structure using a
user defined n-tuple key. So far I've only heard two suggestions: 1)
radically change the typing semantics of Lua with constant tables, or 2)
implement the abstract interface using nested tables and a function
accessor.

At the altitude this discussion is taking place, neither approach is
distinguishable.

In the same spirit as Lua's method calling syntax, what about 3) simply
converting

	local v = t[a,b,c] 

to

	local v = t[a][b][c]

where the compiler inserts the necessary checks for nil tables. Similarly

	t[a,b,c] = v

becomes

	t[a][b][c] = v

where the compiler autovivifies the intermediate tables, just like in Perl.
This syntactic sugar would only be useful as a practical matter where the
number of elements in the tuple-key is fixed, otherwise disambiguiting
intermediate tables from the value being queried would introduce unnecessary
complexity in the language and/or the VM. But in some sense that's almost
preferable, the constraint being akin to strict typing.

Alternatively, 4) Lua could add a new metamethod, __hash, and then use
__hash and __eq when indexing another table. Perhaps to maintain performance
in the common case, like __gc these methods are only used if defined at the
moment setmetatable is invoked.

For my money I would simply choose suggestion #2.