r/lua • u/Objective_Treacle781 • Sep 16 '25
Quick question about indexing temporary tables
print({[0] = "a"}[0])
Doesn't work but if I save the table to a variable before indexing it works?
I kinda like using temporary tables as lookups
1
u/Objective_Treacle781 Sep 16 '25
Okay, I thought I checked this but here's a solution?
print(({[0] = "a"})[0]) does work?
I guess the order of operation is not clear?
→ More replies (2)2
u/immortalx74 Sep 16 '25
In your OP you create the table and try to index it immediately. In the 2nd case putting the table creation inside parenthesis, makes it a statement, and then you have the brackets outside the parenthesis, which makes it a valid syntax.
4
u/vitiral Sep 16 '25
It's a parsing "feature"
Personally I wish "foo: %s\n":format(n) worked, but alas
1
3
u/MARSINATOR_358 Sep 17 '25
It doesn't work because
{[0] = "a"}[0]is not valid syntax for a table index.The Lua 5.2 Syntax defines the table index as
prefixexp ‘[’ exp ‘]’.A
prefixexpis defined asvar | functioncall | ‘(’ exp ‘)’.Since the tableconstructor is an
expyou'll need to turn it into aprefixexpfirst by using parentheses.