lua-users home
lua-l archive

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

On 9 July 2015 at 08:13, William Ahern <> wrote:
> 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.

I'd prefer we reserved that syntax to just send multiple arguments to
an __index metamethod.
i.e. this would print out '1 2 3'

local t = setmetatable({}, {__index=function(t,...) print(...) end})

If a user wanted the vivification they could just do that in their __index:

local vivify_mt = {}
    local v = t[k]
    if select("#", ...) == 0 then
        return v
    if v == nil then
        v = setmetatable({}, vivify_mt)
        t[k] = v
    return v[...]