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

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

问题描述

在lua中是否可以从表示其名称的字符串执行函数?

ie:我有 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

如果另一个表中的函数,如if,则需要使用 loadstring()(或步行每个表) x ='math.sqrt'

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天全站免登陆