asdaw21
asdaw21

Reputation: 33

Possible to call function by string name

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

I am passing a string into this function and want to call a function based off the string name. Is something like this possible without a bunch of if statements?

So ideally, it would be something like this

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

But I'm not sure if something like this is possible in lua.

Upvotes: 1

Views: 132

Answers (1)

Spar
Spar

Reputation: 1752

You need to use [] syntax. [] syntax allows you to use any variable, expression (that evaluates on runtime) or constant.

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

.var syntax is actually identical to ["var"] (syntactic sugar).

Read move about table syntax: https://www.lua.org/pil/2.5.html

Upvotes: 3

Related Questions