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

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

原文链接 https://stackoverflow.com/questions/6803492

点赞
stackoverflow用户734069
stackoverflow用户734069

尝试这个。

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
2011-07-23 21:51:04
stackoverflow用户107090
stackoverflow用户107090

你差点就做对了。试试这个

function fcreate(fs)
  return assert(loadstring("return function (x) return " .. fs.." end"))()
end
2011-07-23 22:35:01
stackoverflow用户151501
stackoverflow用户151501

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

(这意味着在运行时没有办法将字符串转换为 Lua 代码)

2011-07-24 00:11:39