【问题标题】:Convert string to variable name in Lua在 Lua 中将字符串转换为变量名
【发布时间】:2020-04-14 07:55:11
【问题描述】:

在 Lua 中,我有一组表:

Column01 = {}
Column02 = {}
Column03 = {}
ColumnN = {}

我正在尝试根据值动态访问这些表。因此,稍后在程序中,我将创建一个像这样的变量:

local currentColumn = "Column" .. variable

其中变量是一个从01到N的数字。

然后我尝试对数组中的所有元素做一些事情,如下所示:

for i = 1, #currentColumn do
    currentColumn[i] = *do something* 
end

但这不起作用,因为 currentColumn 是一个字符串,而不是表的名称。如何将字符串转换为表名?

【问题讨论】:

  • 您可以将所有列存储在数组colums 中,这样做您将通过columns[variable] 获得所需的列,而无需构造字符串然后通过另一个字符串变量访问变量(您已经将索引存储在variable)

标签: arrays string variables lua naming


【解决方案1】:

如果我理解正确,您是说您希望根据变量名称作为字符串访问变量?我认为您正在寻找的是全局变量_G。 回想一下,在表格中,您可以将字符串作为键。将 _G 想象成一张巨大的表格,其中您创建的每个表格或变量都只是一个值的键。

Column1 = {"A", "B"}
string1 = "Column".."1" --concatenate column and 1. You might switch out the 1 for a variable. If you use a variable, make sure to use tostring, like so:
var = 1
string2 = "Column"..tostring(var) --becomes "Column1"
print(_G[string2]) --prints the location of the table. You can index it like any other table, like so:
print(_G[string2][1]) --prints the 1st item of the table. (A)

因此,如果您想遍历 5 个名为 Column1、Column2 等的表,您可以使用 for 循环创建字符串,然后访问该字符串。

C1 = {"A"} --I shorted the names to just C for ease of typing this example.
C2 = {"B"}
C3 = {"C"}
C4 = {"D"}
C5 = {"E"}
for i=1, 5 do
local v = "C"..tostring(i)
print(_G[v][1])
end

输出

A
B
C
D
E

编辑:我是个傻瓜,我把一切都复杂化了。有一个更简单的解决方案。如果您只想访问循环中的列而不是在某些点访问单个列,那么对您来说更简单的解决方案可能是将所有列放入一个更大的表中,然后对其进行索引。

columns = {{"A", "1"},{"B", "R"}} --each anonymous table is a column. If it has a key attached to it like "column1 = {"A"}" it can't be numerically iterated over.
--You could also insert on the fly.
column3 = {"C"}
table.insert(columns, column3)
for i,v in ipairs(columns) do
print(i, v[1]) --I is the index and v is the table. This will print which column you're on, and get the 1st item in the table.
end

输出:

1   A
2   B
3   C

致未来的读者:如果您想要一个通过名称作为字符串获取表的通用解决方案,那么您想要的第一个解决方案是 _G。如果你有类似提问者的情况,第二种解决方案应该没问题。

【讨论】:

  • 这行得通。但是如果表是本地的呢? _G、_M 和 _ENV 给出编译错误。
猜你喜欢
  • 2011-08-27
  • 2010-12-04
  • 2011-03-24
  • 2011-08-02
  • 2016-04-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多