in LUA - 在 _G 中找到类型为 "function" 的变量如何将参数传递给它

in LUA - having found a variable of type "function" in _G how to pass a parameter to it

我已经成功地在 _G 中的 table 中找到了函数,对于那些不需要参数的函数,我使用如下语法调用它们:

a = _G[t] [f] () 

但有些函数需要参数,我尝试使用

传递它们
a = _G[t] [f] (x)

但是 LUA 的错误消息似乎是说被调用的函数没有收到“x”。

因此我的问题是,如果函数定义为

function t:f (arg)

当我有 t 和 f 的文本字符串时,如何给它一个处理参数?

谢谢

函数定义如

function t:f(arg)

有一个隐含的第一个参数 self 所以定义实际上是一样的:

function t.f(self, arg)

因此,当您调用 a = _G["t"]["f"](x) 时,您会将 x 作为 self 传入,并且 arg 设置为 nil。要正确调用它,您需要做

_G["t"]["f"](_G["t"], arg);

一些示例代码,您可以看到它的实际效果

t = {}

function t:f(arg)
    print(self, arg)
end

_G["t"]["f"]("test")         -- "test   nil"
_G["t"]["f"](_G["t"],"test") -- "table: 00e09750    test"