Assign Two Variables With Only One Variable?

I have been a roblox developer for a long time, and I have seen a lot of ways to make your code simpler and cleaner. My question is whether you can assign two variables like a and b to the same variable like this but without errors:

   local a, b = 8

My only solution would be to do this but it seems lengthy:

   local a, b = 8, 8

Any help would be nice.

4 Likes

Nope (Lua 5.1 Reference Manual), that’s just not how it works in Lua.

If the expressions / right-hand side is really long or annoying to repeat, you can get sorta close like this

local a = a_really_long_expression_that_I_dont_want_to_type_more_than_once
local b = a
2 Likes

just going to drop this here

a, b = 8,a
print(a) -- 8
print(b) -- 8

I don’t know why you’d ever want to do this, but you could also do


Eights = {}
repeat table.insert(Eights,8) until #Eights>10

a,b,c,d,e,f,g = unpack(Eights)

print(a) -- 8
print(d) -- 8
print(g) -- 8
5 Likes

Thank you for your help! I was thinking something like that as well, but was curious if there was any other way.

The first wouldn’t work because it’s initialized at once (image a Tuple), not one by one.
The reason you got 8 on b is because you used globals instead of locals and probably ran that script more than once (meaning a already existed on future runs)
This is further noticeable if you use locals:

local a, b = 8,a
print(a) -- 8
print(b) -- 8

Therefore it’s not a solution.

That’s a valid point. Seems like you’d need a predefined variable for local variables.

local a = 123
local b, c, d = a, a, a

Also worth noting that they’re pass by reference, so not really creating two variables, just synonyms

local ooga = {booga=true}
local spaghetti, ramen, bread = ooga, ooga, ooga

print(spaghetti['booga']) -- true
spaghetti['booga']=false
print(bread['booga']) -- false
1 Like