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

Function LUA:在类中使用函数名(字符串)调用函数,function,oop,lua,Function,Oop,Lua,我试图使用对象的名称调用该对象的函数(我希望使用该名称,因为我将从URL检索函数的名称) 我是LUA的初学者,所以我试着去理解什么是可能的(或者不是!) 在本例中,我希望从主文件执行对象“controllerUser”的函数“creerCompte()” 我已经创建了一个主文件: --We create the controller object local controller = require("controllers/ControllerUser"):new() loc

我试图使用对象的名称调用该对象的函数(我希望使用该名称,因为我将从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)
这是控制器对象

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

提前感谢您的帮助

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


self:method()
self的快捷方式。method(self)
self。method
是Lua函数中
self['method']
的语法糖。用作名称的是变量的名称或表中的键(通常是全局变量表)

如果它是一个全局变量,您当然可以使用
\u G['name'](args…
),或者
\u G[namevar](args…
,如果您在
namevar
变量中有名称。但这很容易在许多方面出现问题(不适用于本地函数或模块内的函数等)

更好(也更安全)的方法是创建一个表,其中只包含您想要提供的函数,并使用您想要用作表键的名称:

local function doOneThing(args)
    -- anything here
end

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

exportFuncs = {
    thing_one = doOneThing,
    someOtherThingToDo = someOtherThingToDo,
}
然后,您可以通过以下名称轻松调用函数:
exportFuncs[namevar](…)