lua - How do I turn a string into an argument? -
i using app touchlua.
i need turn string table argument. way table.
b = {} b[1] = "010,010,draw.blue" function drawbuttons() = 1,2 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()
assuming want function eval
print( eval( "draw.blue" ) )
equivalent print( draw.blue )
, here quick , dirty version:
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" ) )
if using older lua version 5.2, need loadstring
instead of load
, additional setfenv
call. of course, instead of using load
can parse string s
, index table e or _g
manually.
the above code assumes draw
global variable. if want code work local variable need use debug library:
-- same local variable local localdraw = { blue = 3 } print( localdraw.blue ) -- needs debugging information, won't work stripped bytecode! local function locals() local t, i, n, v = {}, 1, debug.getlocal( 2, 1 ) while n ~= nil t[ n ], = v, i+1 n, v = debug.getlocal( 2, ) end return t end print( eval( "localdraw.blue", locals() ) )
Comments
Post a Comment