LUA: calling a function using its name (string) in a class

I am trying to call a function of an object using its name (I would like to use this name because I will get the name of the function from the URL).

I'm starting at LUA, so I'm trying to figure out what is possible (or not!)

In this example, I want to execute the "creerCompte ()" function of the "controllerUser" object from my main file.

I created the main file:

   --We create the controller object
   local controller = require("controllers/ControllerUser"):new()
   local stringAction = "creerCompte" -- Name of the function to call in the controller Object

   --Attempting to call the function stringAction of the object controller
   local action = controller:execute(stringAction)

This is a controller object.

ControllerUser = {}
ControllerUser.__index = ControllerUser

function ControllerUser:new()
    local o = {}
    setmetatable(o, self)
    return o
end

function ControllerUser:execute(functionName)
    loadstring("self:" .. functionName .. "()") --Doesn't work: nothing happens
    getfenv()["self:" .. functionName .. "()"]() --Doesn't work: attempt to call a nil value
    _G[functionName]() --Doesn't work: attempt to call a nil value
    self:functionName() -- Error: attempt to call method 'functionName' (a nil value)
end

function ControllerUser:creerCompte()
   ngx.say("Executed!") --Display the message in the web browser
end

return ControllerUser

Thank you in advance for your help.

+4
source share
2 answers

Try self[functionName](self)instead self:functionName().

self:method()is shortcut for self.method(self)and self.methodis syntactic sugar for self['method'].

+10

Lua . , , - , ( , )

, _G['name'](args...) _G[namevar](args...), namevar. ( ..)

( ) , , , :

local function doOneThing(args)
    -- anything here
end

local function someOtherThingToDo()
    -- ....
end

exportFuncs = {
    thing_one = doOneThing,
    someOtherThingToDo = someOtherThingToDo,
}

: exportFuncs[namevar](...)

+4

All Articles