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

最佳答案

你几乎是对的。试试这个

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

关于lua - 根据表达式文本返回函数的函数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/6803492/

10-15 01:47
查看更多