Create multiple variables using for loop in lua

限于喜欢 提交于 2019-12-24 02:07:40

问题


I want to use a for loop to create multiple varibles (with names that are the same except for the last character) in lua

for i= 1, 10, 1 do
        marker+i = "do things"
    end

pretty much I what I want to get is: marker0, marker1, marker2 and so on. and I guess there is something wrong with marker+i

I get an error. Thank you.


回答1:


You probably don't want to do this actually. Much simpler would be to create a table and create those variables as keys in the table.

t={}
for i=1, 10, 1 do
    t["marker"..i] = "do things"
end

(Note that .. is contatenation and not + in lua. Note also that you need to quote a string and not use it literally.)

But if you really want those to be global variables and not keys in some other table you can generally (depending on environment) do the following

for i=1, 10, 1 do
    _G["marker"..i] = "do things"
end


来源:https://stackoverflow.com/questions/27133159/create-multiple-variables-using-for-loop-in-lua

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