Reputation: 313
local x,y=33,44
I don't know what this format is referred to as, if anything, I couldn't find any keyword. Assigns local x=33; local y=44. Has the gimmick where the assignment of x does not affect the assignment of y, i.e.
x=50
x,y=0,x --x=0,y=50
x=0 --x=0
y=x --y=0
Great. The notation relies on the comma to separate where the first variable assignment ends and the second one begins. My confusion lies with cases with inclusion of statements like this:
local a,b=
33 --a=33 b=nil
for i=1,2 do
a+=i --a=34,b=nil --a=3,b=34
a,b=i,a --a=1,b=34 --a=2,b=3
end
The above makes sense, why does the following addition of a comma create an error though:
local a,b=
33 --a=33 b=nil
for i=1,2 do
a+=i --a=34,b=nil --a=3,b=34
a,b=i,a --a=1,b=34 --a=2,b=3
end,33
From my perspective the above should just be assigning
a= 33 --a=33 b=nil
for i=1,2 do
a+=i --a=34,b=nil --a=3,b=34
a,b=i,a --a=1,b=34 --a=2,b=3
end
b=33
Seems any addition of a comma after I toss in a condition like a loop disallows me to assign the second variable to anything other than defining it within the first? I don't understand the logic here. Are there rules illustrating why this is. I can't find the information. Lacking keywords here.
Upvotes: 1
Views: 1721
Reputation: 28994
local a,b=
33 --a=33 b=nil
for i=1,2 do
a+=i --a=34,b=nil --a=3,b=34
a,b=i,a --a=1,b=34 --a=2,b=3
end
is equivalent to
local a, b = 33, nil
for i=1,2 do
a+=i
a,b=i,a
end
This is syntactically correct. Hence there is no error message.
local a,b=
33 --a=33 b=nil
for i=1,2 do
a+=i --a=34,b=nil --a=3,b=34
a,b=i,a --a=1,b=34 --a=2,b=3
end,33
Is equivalent to
local a,b= 33, nil
for i=1,2 do
a+=i
a,b=i,a
end
,33
You cannot have ,33
isolated in your code. That doesn't make sense. Hence the error.
As Paul already explained, you can only assign a comma separated list of expressions. A for loop is not an expression, it's a statement. It should be obvious that you cannot have a statement in the middle of a comma separated list of expressions.
Upvotes: 2
Reputation: 26794
The above makes sense, why does the following addition of a comma create an error though
Because as described in the Assignment section of the Lua manual, it expects explist
on the right side, which is defined as a comma separated list of expressions: nil | false | true | Numeral | LiteralString | ‘...’ | functiondef | prefixexp | tableconstructor | exp binop exp | unop exp
. None of that allows the statement (a for
loop in your case) to be included.
The example where only 33
is on the right side is still valid, as Lua will assign nil
to all variables on the left side that don't have matches on the right side.
You can assign something arbitrarily complex if you want to, but you need to use an anonymous function and invoke it right away with something like the following:
local a, b = 33, (function()
print("foo")
return 34
end)()
print(b) -- will print `34`
Upvotes: 3