Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

lua multiple assignment

Tags:

lua

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

like image 551
nil Avatar asked Aug 28 '26 05:08

nil


1 Answers

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?

like image 186
Mud Avatar answered Sep 02 '26 12:09

Mud