Question

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.

Was it helpful?

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.

OTHER TIPS

If your variables are local variables, its impossible to do what you want since Lua erases the names during compilation. If your variables are properties of a table (like global variables are) then you can use the fact that table access is syntax sugar for accessing a string property in a table:

--using a global variable
damage1 = 17

--is syntax sugar for acessing the global table
_G.damage1 = 17

--and this is syntax sugar for acessing the "variable1" string property
--of the global table
_G["damage1"] = 17

--and you can build this string dynamically if you want:
_G["damage"..1] = 17

However, as lhf said, it would probably be much more simpler if you stored the variables in an array instead of as separate variables:

damages = {10, 20, 30, 40}

for i=1,4 do
    damages[i] = damages[i] + 1
end

Wouldn't this be the best thing to do?

damages = {}

for i = 0,11 do
    table.insert(damages, love.graphics.newImage("/sprites/damage/damage"..i..".png"));
end

And then call by damages[0], damages[1]. etc.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top