我正在从 Lua 中的字符串创建函数(x)。我使用的代码是
function fcreate(fs)
return assert(loadstring("return function (x) return " .. fs.." end"))()
end
这适用于全局变量,例如
u=fcreate("math.sin(x)")
做正确的事。
但是,它似乎不喜欢局部变量。所以
local c=1
u=fcreate("math.sin(x)+c")
不会工作,因为 c 是本地的。
这是可以修复的吗?
最佳答案
"loadstring does not compile with lexical scoping" ,所以不,它看不到 loadstring
之外的本地人称呼。
Is this fixable?
那要看。为什么首先使用 loadstring? Lua 支持闭包作为第一类值,所以我从你的例子中看不出你为什么需要 loadstring。
你的例子:
u = fcreate("math.sin(x)+c")
无需
loadstring
即可重写或您的 fcreate
功能:u = function(x) return math.sin(x)+c end
这当然是相同的:
function u(x) return math.sin(x) + c end
我可以看到
loadstring
的案例如果您有想要编译成其他函数的用户可配置表达式,但您的情况是本地 c
表明情况并非如此。您是否正在尝试制作某种家庭式的 lamda 语法?
关于lua - 从字符串创建 Lua 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11380379/