lua-users home
lua-l archive

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


Hi all!

I stumbled into this idea while writing a long set-like table. Wouldn't it be nice if the follwing:


set = { a = true, b = true, [1] = true }

could be abbreviated as:

set = { ["a","b",1] = true }

?

In other words I propose to enhance the table constructor syntax to allow not just one expression inside "[]", but an expression list, so that:

[exp1,exp2,exp3,...] = val

would be expanded as

[exp1] = val, [exp2] = val, [exp3] = val, ...

this would greatly simplify writing many-to-one mappings and would also be more symmetric with current typical one-to-many mappings:

exp = {val1, val2, val3, ... }


It seems an easy change and it shouldn't confuse the parser or complicate it too much (there aren't contexts where an expression list can appear inside square brackets, if I'm not mistaken).

This could also interact nicely with multiple returns and varargs:


{ [func()] = true }

will make a set out of all the return values of f; and this would be the set of all the values passed to a vararg func:

{ [...] = true }

Expanding on this, we could write even more complex mappings in an easy way, without writing maps the other way around and then reversing them:

errors = {
 [ "bad arg", "out of range", "invalid type" ] = "resumable",
 [ "core dump", "out of memory", "disk full" ] = "fatal",
}

instead of

errors = { -- silly long way
 ["bad arg"] = "resumable",
 ["out of range"] = "resumable",
 ["invalid type" ] = "resumable",
 ["core dump" ] = "fatal",
 ["out of memory" ] = "fatal",
 ["disk full" ] = "fatal",
}

or (smarter way - having a suitable reverse_map function)

errors = reverse_map {
 resumable = { "bad arg", "out of range", "invalid type" },
 fatal = { "core dump", "out of memory", "disk full" },
}


I wonder why such a clear and readable syntax alternative isn't already in Lua. Since I'm definitely not a language designer I suspect that there are some pitfalls I haven't considered, or maybe it could bloat Lua too much from an implementation POV.

Anyway even if it is a more stupid proposal than it seems to me, I hope to get new insights from whoever will be so kind to share an opinion.

Any feedback appreciated.
TIA

-- Lorenzo