【问题标题】:Lua Calling a function using its name(string)Lua 使用函数名(字符串)调用函数
【发布时间】:2017-09-29 11:17:28
【问题描述】:

我试图通过它的名称调用一个函数,但是因为我试图调用的函数是一个方法,所以我试图获取的所有参数都是 nil。我应该如何使用所有参数调用此函数?

这是我正在尝试做的一个小例子:

local s = "hi"    
local test = {}

function test:hi(n)
    print(n)
end

test[s]("hello")

打印 --> 无

【问题讨论】:

  • 提示:function test.hi(n) ... endfunction test:hi(n) ... end 有什么区别?

标签: function oop lua


【解决方案1】:

这个:

function test:hi(n)
  print(n)
end

是否完全等同于:

function test.hi(self, n)
  print(n)
end

所以你可以通过这样做得到你正在寻找的结果:

test[s](test, "hello")

或者看到test参数没有被使用,你也可以这样称呼它:

test[s](nil, "hello")

希望这会有所帮助。

【讨论】:

  • 不是function test.hi(test, n),而是function test.hi(self, n)
  • 啊,对了,对不起。我确定了答案。
猜你喜欢
  • 2010-12-19
  • 2014-11-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-10
  • 2019-11-07
  • 1970-01-01
  • 2011-09-18
相关资源
最近更新 更多