It would seem on the surface that variable assignment and table constructors do a similar thing. Why then are table constructors considered ‘expressions’ while variable assignments are considered ‘statements’?
It would seem on the surface that variable assignment and table constructors do a
Share
Table constructors evaluate to tables1
The “assignments” (
=symbols) inside a table constructor are merely the syntax used to initialize fields in the table – they are not variable assignments. The syntax looks similar with the=, but that is only a superficial similarity: do not confuse the two different syntax constructs.Consider if Lua used the same syntax as JavaScript, then it would be
and it would be “clear” that
x: 2is not a variable assignment but a field initializer. Of course, Lua syntax dictates that it is written ast = {x = 2}, but the distinction idea holds. There are two different constructs and the{x = 2}table constructor does not cause side-effects or variable assignment.1 It wouldn’t make much sense if tables couldn’t be assigned for later use! Since only expressions can appears on the right-hand side of an assignment then table constructors must be expressions so the resulting tables (which are values) can be assigned to variables (or passed to functions, etc).
Also note that Lua has a stronger separation of (assignment) statements and expressions than languages like C.