lua 从带有函数名的字符串调用函数 [英] lua call function from a string with function name

查看:25
本文介绍了lua 从带有函数名的字符串调用函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在lua中是否可以从代表其名称的字符串中执行一个函数?
即:我有 string x = "foo",是否可以执行 x() ?

Is it possible in lua to execute a function from a string representing its name?
i.e: I have the string x = "foo", is it possible to do x() ?

如果是,语法是什么?

推荐答案

调用全局命名空间中的函数(如@THC4k 提到的)很容易完成,不需要loadstring().

To call a function in the global namespace (as mentioned by @THC4k) is easily done, and does not require loadstring().

x='foo'
_G[x]() -- calls foo from the global namespace

如果函数在另一个表中,例如 x='math.sqrt',您将需要使用 loadstring()(或遍历每个表).

You would need to use loadstring() (or walk each table) if the function in another table, such as if x='math.sqrt'.

如果使用了 loadstring(),您不仅要在括号中添加省略号 (...) 以允许参数,还要添加 return 到前面.

If loadstring() is used you would want to not only append parenthesis with ellipse (...) to allow for parameters, but also add return to the front.

x='math.sqrt'
print(assert(loadstring('return '..x..'(...)'))(25)) --> 5

或走桌子:

function findfunction(x)
  assert(type(x) == "string")
  local f=_G
  for v in x:gmatch("[^%.]+") do
    if type(f) ~= "table" then
       return nil, "looking for '"..v.."' expected table, not "..type(f)
    end
    f=f[v]
  end
  if type(f) == "function" then
    return f
  else
    return nil, "expected function, not "..type(f)
  end
end

x='math.sqrt'
print(assert(findfunction(x))(121)) -->11

这篇关于lua 从带有函数名的字符串调用函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆