Oh, and did I say that I hate the notation forcing us to use [] for keys in table constructors ?
- {[10]=11}, why not just {10=11} ???
- {['a string']='something'}, why not just {'a string'='something') ?
The notation using [] is just needed when keys are expressions with arbitrary types, but it should never be needed if keys are static strings or numbers. But in fact, given that "=" is reserved for assignment instructions, the [] is never needed syntaxically: in table constructors, the "=" replaces the assignment, but it is in fact a true assignement (of a key), so this shouldbe valid as well:
- {sin(x) = 1}, i.e. the same as today's {[sin(x)] = 1}
And a useful extension would be to allow BOTH the key part or the value part to be "begin end" blocks containing a return statement, to compute keys or values without hacing to use local anonymous function declaration followed by a call:
- Today we can write { [fun(x)] = fun(y), } with predeclared function names, or
{[(function(x) return 0)()] =
(function(x) return 1)(), }
- But we could as well just write
{ fun(x) = fun(y), }, or
{ begin return 0 end] =
begin return 1 end, }
There's no justification at all of these [] in Lua table constructors for keys; they are only syntaxically removable when keys are static strings and the string value has the syntax of an identifier, so you can remove the [] and the '' simultaneously as in { key = 0, }. Lua has already made a compromize by accepting to drop the [] only in some cases, but this can be safely generalized (while keeping the distinction between { k =0, } which uses a new static string 'k' and
{ (k) =0, } or
{ [k] =0, } for a key computed as the value of the _expression_ (k), i.e. the content of varaible k in scope.
The only restriction is { identifier = anything }: this identifier is always a new key and not a reference to a variable with the same identifier in the local scope before the full table constructor. The constructor itself does not create a new scope, so the
keys
"assigned" in the constructor are not visible in any internal scope, but if needed we could as well allow declaring a local scope inside table constructors for defining variables that would not become member keys of the table, by allowing the insertion of "local" statements :
- { local k = 10, v = 11; (k) = v}; note the parentheses, would be the same as: { 10 = 11 }, or today's { [10] = 11 }
As well we could have local variable declarations inside () subexpressions so that () would create a local scope as well:
- y=20; x = (local y = 10; y*y); would be the same as: y= 20; x = (10 * 10); i.e. the local y in the subexpression as no effect on the external y.
Using [] for keys of tables constructors in Lua should be clearly deprecated in all cases (not just "some" cases as today), even if they way still be used (they would
be
in fact always equivalent to parentheses in the new extended syntax, when we need them to distinguish variable names and static string keys)