簡體   English   中英

Lua中將字符串轉換為變量名

[英]Convert string to variable name in Lua

在 Lua 中,我有一組表:

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

我正在嘗試根據值動態訪問這些表。 所以,稍后在程序中,我創建了一個像這樣的變量:

local currentColumn = "Column" .. variable

其中變量是一個數字 01 到 N。

然后,我嘗試對數組中的所有元素執行某些操作,如下所示:

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

但這不起作用,因為 currentColumn 是一個字符串而不是表的名稱。 如何將字符串轉換為表名?

如果我理解正確,您是說您想根據名稱作為字符串訪問變量? 我認為您正在尋找的是全局變量_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)

因此,如果您想遍歷名為 Column1、Column2 等的 5 個表,您可以使用 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 的解決方案就是您想要的。 如果你有像提問者這樣的情況,第二種解決方案應該沒問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM