我正在使用应用TouchLua。
我需要将表中的字符串转换为参数。这是我想表的唯一方法。
b = {}
b[1] = "010,010,draw.blue"
function drawButtons()
for i = 1,2 do
draw.fillrect(tonumber(string.sub(b[i],1,3)), tonumber(string.sub(b[i],5,7)), tonumber(string.sub(b[i],1,3))+10, tonumber(string.sub(b[i],5,7)),string.sub(b[i],9))
end
end
drawButtons()
答案 0 :(得分:2)
假设您需要一个函数eval
,以便print( eval( "draw.blue" ) )
大致相当于print( draw.blue )
,这里有一个快速而又脏的版本:
local function eval( s, e )
return assert( load( "return "..s, "=eval", "t", e or _G ) )()
end
-- global variable
draw = { blue = 2 }
print( draw.blue )
print( eval( "draw.blue" ) )
如果您使用的是旧的Lua版本而不是5.2,则需要loadstring
而不是load
以及额外的setfenv
来电。当然,您可以手动解析字符串load
并索引表s
,而不是使用e or _G
。
上面的代码假设draw
是一个全局变量。如果您希望代码使用本地变量,则需要使用调试库:
-- same for local variable
local localdraw = { blue = 3 }
print( localdraw.blue )
-- needs debugging information, so won't work with stripped bytecode!
local function locals()
local t, i, n, v = {}, 1, debug.getlocal( 2, 1 )
while n ~= nil do
t[ n ], i = v, i+1
n, v = debug.getlocal( 2, i )
end
return t
end
print( eval( "localdraw.blue", locals() ) )