LUA:在类中使用其名称(字符串)调用函数

Che*_*bye 4 oop lua function

我试图使用其名称调用对象的函数(我想使用该名称,因为我将从URL检索函数的名称).

我是LUA的初学者,所以我试着了解什么是可能的(或不是!)

在这个例子中,我想从我的主文件中执行对象"controllerUser"的函数"creerCompte()".

我创建了一个主文件:

   --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)
Run Code Online (Sandbox Code Playgroud)

这是控制器对象

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
Run Code Online (Sandbox Code Playgroud)

在此先感谢您的帮助

Pau*_*nko 10

尝试self[functionName](self)而不是self:functionName().

self:method()是一个快捷方式,self.method(self)并且self.method是语法糖self['method'].