简体   繁体   English

在lua中使用for循环创建多个变量

[英]Create multiple variables using for loop in lua

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循环在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. 我想得到的几乎是:marker0,marker1,marker2等。 and I guess there is something wrong with marker+i 我想标记+ i出了点问题

I get an error. 我得到一个错误。 Thank you. 谢谢。

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.) (请注意, ..是污染,而不是lua中的+ 。还请注意,您需要引用字符串,而不能按字面意义使用它。)

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM