Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

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

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?

3 comments

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... :-/

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.

0

Did you try it with two different variables? Or does this only occur with one variable?

2 answers

✓ Accepted answer

"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.

This discussion is preserved as it was. New answers, comments, and votes are closed.