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

浪子不回头ぞ 提交于 2019-12-23 21:15:28

问题


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:


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.




回答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



回答3:


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.



来源:https://stackoverflow.com/questions/17264838/setting-a-variable-in-a-for-loop-with-temporary-variable-lua

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!