简体   繁体   English

在 LUA 中 - 在 _G 中找到了“函数”类型的变量,如何将参数传递给它

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

I have successfully found functions in a table within _G and, for those that do not expect arguments, I've called them with a syntax such as:我已经成功地在 _G 的表中找到了函数,对于那些不期望 arguments 的函数,我使用如下语法调用它们:

a = _G[t] [f] () 

but some functions are expecting arguments and I have tried to pass them using但是有些功能需要 arguments 并且我尝试使用它们传递它们

a = _G[t] [f] (x)

but the error message from LUA seems to say that the called function has not received "x".但是来自 LUA 的错误消息似乎说被调用的 function 没有收到“x”。

My question therefore is, if the function is defined as因此,我的问题是,如果 function 被定义为

function t:f (arg)

how do I give it an argument to process when I have the text strings for t and f?当我有 t 和 f 的文本字符串时,如何给它一个要处理的参数?

Thanks谢谢

A function defined like A function 定义如下

function t:f(arg)

has a implicit first arg of self so the definition is actually the same as:具有self的隐式第一个参数,因此定义实际上与以下内容相同:

function t.f(self, arg)

So with this, when you call a = _G["t"]["f"](x) you are passing in x as self and arg is set to nil.因此,当您调用a = _G["t"]["f"](x)时,您将x作为 self 传入,并且arg设置为 nil。 To call this properly you need to do要正确调用它,您需要这样做

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

Some example code so you can see this in action一些示例代码,以便您可以看到它的实际效果

t = {}

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM