lua-users home
lua-l archive

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


> according to the reference manual multi-assignment is possible, eg,

> x, y = 1, 2;

> Does this apply within tables as well? eg,

No.

> table = {
>                x, y = 1, 2;
> }

This is more or less equivalent to:
table = {}
table[1] = x
table.y = 1
table[2] = 2

> Running this through lua and printing the table gives me
> 2 = 2
> y = 1

Yep. x was presumably nil before you did that statement.

> Am I misunderstanding something or is the only way to do this to declare 
the table
>  table = {};
> and then place into it
>   table.x, table.y = 1, 2;
> which does do the right thing, but is not what I was trying to do

I think what you want is:

  table = {x = 1, y = 2}

Creating a table is not the same as assignment. A multiple assignment lets 
you assign variables "simultaneously" so that:
  x, y = y, x
does the right thing. This would not make sense inside a table 
constructor:
  table = {x = y, y = x}
Here the x, y on the left of the equals sign are table keys, while the x, 
y on the right hand sides are variables (either local or global) and 
completely unrelated syntactically.

Note that evaluation and assignment order is undefined both for multiple 
assignment statements and for table constructors. (That is, you should not 
count on things happening left to right, because generally they don't.)

HTH,

R.