2

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.

1

3 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the fast answer! I will be able to access this variable as if it was a normal variable, yes?
2

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

1 Comment

I made a local table, instead of making a local variable.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.