How does multiple assignment work when the identifiers are the same?

I gave this code a test.

local foo, foo = 1, 2
print(foo)

Printed 2. But when they were globals this printed 1. Why is this?

What is going on here that causes the first assignment to win, when the second assignment is done first? Is this like a special scope?

Is there any other nuances to be careful of?

1 Like

The local keyword.assigns the identifier last if the name is same apprently is set.

local foo, foo, foo, foo, bar = 1, 2, 3, 4, 5
print(foo, bar) --> 4 5

While without the local keyword, the first one is assigned.

local foo, bar
foo, foo, foo, foo, bar = 1, 2, 3, 4, 5
print(foo) --> 1, 5

I think got something to do with the local keyword (or locally assigned variable because function parameter with the same identifier also gets the last value).

Edit: It turns out there aren’t in any order.

The order in which multiple assignments are performed is not defined. This means you shouldn’t assume the assignments are made from left to right. If the same variable or table reference occurs twice in the assignment list the results may surprise you.

a, a = 1, 2 > print(a) 1

In the above example Lua does assignments from right-to-left, e.g. a=2 and then a=1 . However we shouldn’t depend on this being consistent in future versions of Lua. You should use separate assignment statements if the order of assignment is important to you.

1 Like