Create multiple variables using for loop in lua

2019-07-20 06:31发布

问题:

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