Search code examples
functionluaglobal

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:

a = _G[t] [f] () 

but some functions are expecting arguments and I have tried to pass them using

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

but the error message from LUA seems to say that the called function has not received "x".

My question therefore is, if the function is defined as

function t:f (arg)

how do I give it an argument to process when I have the text strings for t and f ?

Thanks


Solution

  • A function defined like

    function t:f(arg)
    

    has a implicit first arg of self so the definition is actually the same as:

    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. 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"