Lua/pico8: 在不访问 _G 的情况下将 str 转换为变量 table
Lua/pico8: Converting str to variable without access to _G table
我正在寻找迭代一些类似命名的变量。 a_1,a_2,a_3=1,2,3
所以,而不是使用:
if a_1>0 then a_1-=1 end
if a_2>0 then a_2-=1 end
if a_3>0 then a_3-=1 end
我可以这样做:
for i=1,3 do
if a_'i'>1 then a_'i'-=1 end --syntax is wrong here
end
不确定如何进行此操作,如前所述,pico8 中无法访问 _G 库。 var-=1 就是 var=var-1。鉴于有像 tostr() 和 tonum() 这样的函数,我想知道是否有 tovar() 的技巧。基本上需要一种方法将 i 值转换为我的变量名中的字母并将其连接到变量名......在条件语句中。或者其他方法(如果有的话)。
不确定 pico 8 使用哪个 Lua 版本,但对于 LuaJIT,您可以尝试使用 loadstring
,load
用于 Lua 5.2+(我知道,不是最好的解决方案):
for i = 1, 3 do
local x
loadstring("x = a_" .. tostring(i))()
if x > 1 then
x = x - 1
loadstring("a_" .. tostring(i) .. " = x")()
end
end
在Lua中,如有疑问,请使用table。
在这种情况下,您可以将 3 变量放在 table 开头,然后 unpack 放在结尾:
local a={a_1,a_2,a_3}
for i=1,3 do
if(a[i]>1) a[i]-=1
end
a_1,a_2,a_3=unpack(a)
我正在寻找迭代一些类似命名的变量。 a_1,a_2,a_3=1,2,3
所以,而不是使用:
if a_1>0 then a_1-=1 end
if a_2>0 then a_2-=1 end
if a_3>0 then a_3-=1 end
我可以这样做:
for i=1,3 do
if a_'i'>1 then a_'i'-=1 end --syntax is wrong here
end
不确定如何进行此操作,如前所述,pico8 中无法访问 _G 库。 var-=1 就是 var=var-1。鉴于有像 tostr() 和 tonum() 这样的函数,我想知道是否有 tovar() 的技巧。基本上需要一种方法将 i 值转换为我的变量名中的字母并将其连接到变量名......在条件语句中。或者其他方法(如果有的话)。
不确定 pico 8 使用哪个 Lua 版本,但对于 LuaJIT,您可以尝试使用 loadstring
,load
用于 Lua 5.2+(我知道,不是最好的解决方案):
for i = 1, 3 do
local x
loadstring("x = a_" .. tostring(i))()
if x > 1 then
x = x - 1
loadstring("a_" .. tostring(i) .. " = x")()
end
end
在Lua中,如有疑问,请使用table。
在这种情况下,您可以将 3 变量放在 table 开头,然后 unpack 放在结尾:
local a={a_1,a_2,a_3}
for i=1,3 do
if(a[i]>1) a[i]-=1
end
a_1,a_2,a_3=unpack(a)