根据表达式文本返回函数的函数
我想创建一个函数(称之为 fcreate),当给定一个字符串时,它返回一个 Lua 函数。例如,我应该能够说
f=fcreate("math.sin(x)+math.cos(x)")
print(f(2)) -- evaluates sin(2)+cos(2)
print(f(3)) -- evaluates sin(3)+cos(3)
To make things simple, the string will just be a function of x.
我已尝试以下操作,但它不起作用:
function fcreate(fs)
assert(loadstring("local f=function (x) return ".." end"))
return f
end
由于某种原因,返回的 f 为零。
I would like to create a function (call it fcreate) that when given a string, returns a Lua function. For example, I should be able to say
f=fcreate("math.sin(x)+math.cos(x)")
print(f(2)) -- evaluates sin(2)+cos(2)
print(f(3)) -- evaluates sin(3)+cos(3)
To make things easy, the string will just be a function of x.
I have tried the following but it did not work:
function fcreate(fs)
assert(loadstring("local f=function (x) return ".." end"))
return f
end
For some reason the f which is returned is nil.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
试试这个。
如果有参数,可以使用
...
表示法来获取。但如果你绝对需要命名参数:Try this.
If there are parameters, you can use
...
notation to get them. But if you absolutely need named parameters:你几乎是对的。试试这个
You almost had it right. Try this
CoronaSDK 是沙盒的,因此
loadstring
、dostring
、loadfile
和dofile
均不可用。(这意味着没有办法在运行时从字符串转换为 lua 代码)
CoronaSDK is sand-boxed, so
loadstring
,dostring
,loadfile
, anddofile
are all unavailable.(this means that there isn't a way to go from a string to lua code at runtime)