I ran the following test code:
function a() print("a"); return 1; end function b() print("b") return 2; end x, x = a(), b(); print(x)
The result surprised me. The output is as follows:
a b 1
What happens here that causes the first assignment to win if the second assignment is the one that executes first? Is it a special form of scope?
What other nuances are there to be careful of here?
"In a multiple assignment, Lua first evaluates all values and only then executes the assignments." -http://www.lua.org/pil/4.1.html
Lua will check the values you want to assign to the variables before actually doing any assigning. Look at that url for a more in depth explanation. I'm guessing each value gets added to a stack (If you do not know what a stack is, it is like an array which variables in the current scope get added to). Each value goes onto the top of the stack when it is added. So in this case the stack will look like this.
2
1
When assigning the values to the variables it would makes sense to just pop the top value of the stack and assign it to the right most variable and works your way to the left, popping the stack each time you assign a new variable. So the right most x would get 2 since it is on the top of the stack, and then the next x will get 1 since its the next value on the top of the stack overwriting the previous value.
Btw this also happens.
function a() print("a"); return 1; end function b() print("b") return 2; end function c() print("c") return 3; end a, x, x = a(), b(), c(); print(x)
a
b
c
2
Hope that makes sense :s
I think since you did labeled x as 2 variables it just returned the first value? + maybe if you did print(x, x) it would of printed both.
Locked by User#19524
This question has been locked to preserve its current state and prevent spam and unwanted comments and answers.
Why was this question closed?