字符串到lua函数?

twe*_*ypi 2 lua closures

我有一个字符串,如:

local func = "1 == 3"
Run Code Online (Sandbox Code Playgroud)

如何将其转换为执行函数并从另一个函数中获取结果?喜欢:

function CheckFunc(func)
 local ret = functon() return func end

 return ret
end
Run Code Online (Sandbox Code Playgroud)

Kam*_*olo 8

loadstring() 是你正在寻找的功能:)

在你的情况下,它将被用作: local func = loadstring("return (1==3)")

  • +1你是`loadstring()`比我的好 (2认同)

Hen*_*nyH 6

local func = "1 == 3"

function wrap(s)
    return loadstring("(function() return "..s.." end)()")
end

funcWrapped = wrap(func)

if funcWrapped() then
    print "One eqauls Three"
else
    print "One doesn't equal Three"
end
Run Code Online (Sandbox Code Playgroud)

会输出

One doesn't equal Three
Run Code Online (Sandbox Code Playgroud)

注意:您应该使用@ Kamiccolo loadstring代替我的wrap