基于表达式文本返回函数的函数

时间:2011-07-23 21:43:18

标签: lua

我想创建一个函数(称之为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)

为简单起见,字符串只是x的函数。

我尝试过以下但是没有用:

function fcreate(fs)
  assert(loadstring("local f=function (x) return ".." end"))
  return f
end

由于某种原因,返回的f是零。

3 个答案:

答案 0 :(得分:4)

试试这个。

function fcreate(fs)
  local f = assert(loadstring("return " .. fs))
  return f
end

如果有参数,您可以使用...表示法来获取它们。但如果你绝对需要命名参数:

function fcreate(fs)
  local f = assert(loadstring("local x = ...; return " .. fs))
  return f
end

答案 1 :(得分:2)

你几乎把它弄好了。试试这个

function fcreate(fs)
  return assert(loadstring("return function (x) return " .. fs.." end"))()
end

答案 2 :(得分:0)

CoronaSDK是沙盒,因此loadstringdostringloadfiledofile都不可用。

(这意味着在运行时没有办法从字符串转到lua代码)