Search code examples
for-looplualove2d

Setting a variable in a for loop (with temporary variable) Lua


I have a for loop in lua, and I'm trying to set variables inside that for loop using the iterator variable. I need it to set these variables:

damage1
damage2
damage3
damage4
damage5
damage6
damage7
damage8
damage9
damage10
damage11

Of course I'm not going to assign them all, as that would be breaking the rules of D.R.Y. (Don't Repeat Yourself). This is what I figured would work:

for i = 0, 11 do
    damage..i = love.graphics.newImage('/sprites/damage/damage'..i..'.png')
end

Don't mind the love.graphics.newImage(), that's just a function in the framework I'm using. Anyways, can someone help?

Thanks in advance.


Solution

  • If you want to set global variables, set _G["damage"..i].

    If you want to set local variables, you're out of luck.

    Consider setting damage[i] instead.