如何使用字符串名调用函数

function AIORotation:SetRotation(val)
    if val == "abcd" then
        self.db.profile.activeRotation = AIORotation.aaaa:new()
    elseif val == "dddd" then
        self.db.profile.activeRotation = AIORotation.dddd:new()
    end
end

我正在将一个字符串传递到这个函数中,并希望根据字符串名称调用函数。是否有可能在没有大量 if 语句的情况下实现这样的事情?

所以理想情况下,会是这样的

function AIORotation:SetRotation(val)
    self.db.profile.activeRotation = AIORotation.<INSERT_VAL_HERE>:new()
end

但是我不确定在 Lua 中是否有可能这样做。

点赞
用户8621712
用户8621712

你需要使用 [] 语法。[] 语法允许你使用任何变量、表达式(在运行时计算)或常量。

function AIORotation:SetRotation(val)
    self.db.profile.activeRotation = AIORotation[val]:new()
end

.var 语法实际上与 ["var"] 相同(语法糖)。

阅读更多关于表格语法的内容:https://www.lua.org/pil/2.5.html

2020-12-04 18:59:59