我試圖使用 for 回圈創建像這樣的變數..
TPidL1 = Load('TPidL1', '')
TPidL2 = Load('TPidL2', '')
TPidL3 = Load('TPidL3', '')
TPidL4 = Load('TPidL4', '')
TPidL5 = Load('TPidL5', '')
閱讀其他帖子后,我嘗試了這個但沒有運氣
for z = 1, 5, 1 do
"TPidL"..z = Load('TPidL'..tostring(z), '')
end
有什么想法可以更好地解決這個問題嗎?
謝謝
uj5u.com熱心網友回復:
只需使用常規表而不是弄亂全域變數..?
TPidLs = {}
for z = 1, 5, 1 do
TPidLs[z] = Load('TPidL' .. tostring(z), '')
end
uj5u.com熱心網友回復:
你可以通過全域命名空間做到這一點_G:
for z = 1, 5 do
_G["TPidL"..z] = "TPidL"..z
end
print(TPidL1,TPidL2,TPidL3,TPidL4,TPidL5)
uj5u.com熱心網友回復:
好吧,AFAIK 直接不可能,但是 Lua 非常靈活,有一種方法。關鍵是要了解所有全域變數和函式都簡單地存盤在一個名為_ENV的簡單 Lua 表中。一個簡單的例子來強調這一點:
MyVariable = "Hello"
for Key, Value in pairs(_ENV) do
print(Key,Value)
end
此代碼將顯示如下內容:
loadfile function: 0000000065b9d5a0
os table: 0000000000e19f20
collectgarbage function: 0000000065b9d0a0
io table: 0000000000e18630
error function: 0000000065b9d020
_VERSION Lua 5.4
_G table: 0000000000e11890
print function: 0000000065b9cd60
warn function: 0000000065b9ccc0
arg table: 0000000000e19ba0
table table: 0000000000e18c50
type function: 0000000065b9c780
next function: 0000000065b9cea0
ipairs function: 0000000065b9ce50
assert function: 0000000065b9d6f0
debug table: 0000000000e19f60
rawget function: 0000000065b9cbc0
load function: 0000000065b9d4a0
coroutine table: 0000000000e18c90
pairs function: 0000000065b9d380
string table: 0000000000e19a20
select function: 0000000065b9c890
tostring function: 0000000065b9c860
math table: 0000000000e19a60
setmetatable function: 0000000065b9d2d0
MyVariable 1
dofile function: 0000000065b9d670
utf8 table: 0000000000e19d20
rawequal function: 0000000065b9cc70
pcall function: 0000000065b9c7e0
tonumber function: 0000000065b9c930
rawlen function: 0000000065b9cc10
xpcall function: 0000000065b9c6e0
require function: 0000000000e177c0
package table: 0000000000e17840
rawset function: 0000000065b9cb60
getmetatable function: 0000000065b9d610
就是這樣:_ENV 是一個簡單的表,它在函式名和它的實作之間以及變數名和它的值之間建立了聯系。關于你的問題,我完全不知道Load函式的定義是什么。
但是如果你想動態生成變數名,你可以嘗試:
for Index = 1, 5 do
_ENV["MyVariable"..Index] = Index
end
print(MyVariable1)
print(MyVariable2)
print(MyVariable3)
print(MyVariable4)
print(MyVariable5)
它應該列印:
> print(MyVariable1)
1
> print(MyVariable2)
2
> print(MyVariable3)
3
> print(MyVariable4)
4
> print(MyVariable5)
5
>
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/526649.html
標籤:for循环变量lua
