如何通过字符串构建一个Lua函数?
- 内容介绍
- 相关推荐
本文共计340个文字,预计阅读时间需要2分钟。
我正在Lua中创建一个字符串函数(x)。我使用的代码是:
luafunction fcreate(fs) return assert(loadstring(return function (x) return .. fs .. end))()end
这适用于全局变量,例如:
luau=fcreate(math.sin(x))
我正在从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”,所以不,它看不到loadtring调用之外的本地人.Is this fixable?
那要看.为什么你首先使用loadtring? Lua支持闭包作为第一类值,所以我从你的例子中看不出为什么你需要loadtring.
你的例子:
u = fcreate("math.sin(x)+c")
可以在不需要loadtring或你的fcreate函数的情况下重写:
u = function(x) return math.sin(x)+c end
这当然与以下相同:
function u(x) return math.sin(x) + c end
如果你有用户可配置的表达式,你想要编译成其他函数,我可以看到一个loadtring的情况,但你的情况与本地c表明并非如此.你想尝试一些自制的lamda语法吗?
本文共计340个文字,预计阅读时间需要2分钟。
我正在Lua中创建一个字符串函数(x)。我使用的代码是:
luafunction fcreate(fs) return assert(loadstring(return function (x) return .. fs .. end))()end
这适用于全局变量,例如:
luau=fcreate(math.sin(x))
我正在从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”,所以不,它看不到loadtring调用之外的本地人.Is this fixable?
那要看.为什么你首先使用loadtring? Lua支持闭包作为第一类值,所以我从你的例子中看不出为什么你需要loadtring.
你的例子:
u = fcreate("math.sin(x)+c")
可以在不需要loadtring或你的fcreate函数的情况下重写:
u = function(x) return math.sin(x)+c end
这当然与以下相同:
function u(x) return math.sin(x) + c end
如果你有用户可配置的表达式,你想要编译成其他函数,我可以看到一个loadtring的情况,但你的情况与本地c表明并非如此.你想尝试一些自制的lamda语法吗?

