Reputation: 295
is there any way of multiple assignment in lua such that the missing values on the right side are not considered as nil ?
smth analogous to
a,b,c = 1
but getting
a = 1, b = 1, c = 1
as result.
Unfortunately,
a = b = c = 1
doesn't work.
I need this because I might have complex tables on the right side and I want to keep it short and simple (without any additional variables).
Upvotes: 5
Views: 13919
Reputation: 79
I hope this will work for you
function push(n, value)
if n <= 0 then
return
elseif n == 1 then
return value
else
return value, push(n - 1, value)
end
end
k, l, o, p = push(3, "foo")
print(k)
print(l)
print(o)
print(p)
-- Output:
-- foo
-- foo
-- foo
-- nil
Upvotes: 4
Reputation: 28991
Nope.
Your first example (multiple assignment) already has clearly defined semantics, so Lua would need an addition operator/keyword/something to indicate a desire for different semantics (repeating the last r-value). It doesn't.
Your second example (chaining together assignments, ala C) requires assignments to be expressions, whereas in Lua they are statements.
The closest you could get would be defining a function that pushes a value onto the stack a bunch of times:
function push(x)
return x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x
end
Then you could say:
a,b,c,d,e,f,g = push(t)
But that's pretty kludgey.
Out of curiosity, why do you need a bunch of different references to the same table in the same scope?
Upvotes: 6
Reputation: 54589
You could use a function:
local a,b,c = (function(t) return t,t,t; end)({1,2,3});
Still, I'd prefer the obvious solution: Just use two lines
local a = {1,2,3};
local b,c = a,a;
Upvotes: 4
Reputation: 14565
No, there is no shortcut for this AFAIK.
Also, this probably wouldn't work the way you'd want for table values anyways.
local some_tbl = {a = 1, b = 2, c = 3}
-- you just assigned the same table to both variables
local a,b = some_tbl, some_tbl
a.a = 5
print(a.a, b.a)
the above code outputs:
>lua -e "io.stdout:setvbuf 'no'" "junk.lua"
5 5
you just changed the a value of the tables on both variables (which is probably not what you wanted, you probably wanted the same table definition assigned to each variable, but each table holds different data).
when i have code where i'm working with seperate copies of the same table structure, i write a getter function to return new copies with the same definition. which if used in the code above, would look like this:
function get_TableLayout1()
-- return separate copies of the same table layout
return {a = 1, b = 2, c = 3}
end
local a,b = get_TableLayout1(), get_TableLayout1()
a.a = 5
print(a.a, b.a)
which prints out:
>lua -e "io.stdout:setvbuf 'no'" "junk.lua"
5 1
as expected.
Upvotes: 3