我想知道是否有一种方法可以加载'函数从局部变量而不是全局变量获取变量值?
说我有这样的字符串' trade.version == 2'我想用' load'来执行函数内部以交易为参数。
function doTest( trade, test )
-- inside the string 'test', I would like that any reference to 'trade'
-- refer to the function parameter instead of a global variable
if ( assert(load("return "..test))() ) then
-- do something
end
end
a_userdata = { version = 2 }
-- Calling the function above
doTest( a_userdata , "trade.version == 2" )
[string "return trade.version == 2"]:1: attempt to index global 'trade' (a nil value)
stack traceback:
[string "return trade.version == 2"]:1: in main chunk
stdin:2: in function 'doTest'
stdin:1: in main chunk
[C]: in ?
作为一种解决方法,我已经定义了一个全局变量,它的工作非常好。 但我想避免这个全局变量。
非常感谢
答案 0 :(得分:1)
function doTest( trade, test )
-- inside the string 'test', I would like that any reference to 'trade'
-- refer to the function parameter instead of a global variable
if assert(load("local trade = ...; return "..test))(trade) then
-- do something
print('Yes, version equals to 2')
end
end
a_userdata = { version = 2 }
-- Calling the function above
doTest( a_userdata , "trade.version == 2" )