Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
7

How does execution order in multiple assignments to only one variable? [closed]

Asked by
BlueTaslem 18071 Moderation Voter Administrator Community Moderator Super Administrator
9 years ago

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?

0
I've got nothing, I would think it would be because the first x was assigned, but you had another assigned value for x... :-/ M39a9am3R 3210 — 9y
0
My interpretation: Lua eva.Lua.tes each expression from left to right, but after eva.Lua.ting it, assigns it from right to left, resulting in the above result. blocco 185 — 9y
0
Did you try it with two different variables? Or does this only occur with one variable? blocco 185 — 9y

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?

2 answers

Log in to vote
9
Answered by
magnalite 198
9 years ago

"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

Ad
Log in to vote
-2
Answered by 9 years ago

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.