Schaka
Schaka

Reputation: 772

How to pass arguments to a function within a table?

First of all, I'm stuck with Lua 5.0, because I'm developing for the WoW API (a client built from 2006). Why torture myself? Because I get a kick out of seeing what's possible.

So here is my question: I have a table, that contains a bunch of functions, for example, this one:

function Questie:UNIT_AURA(unitId)
    --log("UnitID: "..unitId)
end

I have another function, which is supposed to automatically route to that function (and it does, to an extent).

function Questie:OnEvent()
    Questie[event](arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10)
end

In this case, event is a global variable, which is equal to the name of the function, for example UNIT_AURA. arg1 to arg10 are also global and should be passed to whatever function event leads to. The function is called just fine, but all the parameters are nil (even if they exist in Questie:OnEvent.

So my question is, how do I make them get passed properly? Evidently, I'm doing something wrong.

Upvotes: 0

Views: 458

Answers (1)

akaRem
akaRem

Reputation: 7638

Here is your mistake (as I see it)

function Questie:UNIT_AURA(unitId)
    --log("UnitID: "..unitId)
end

— that declaration is equivalent to

function Questie.UNIT_AURA(self, unitId)
    --log("UnitID: "..unitId)
end

you can call it like this:

Questie.UNIT_AURA(Questie, unitId)

or like this

Questie['UNIT_AURA'](Questie, unitId)

or like this

Questie:UNIT_AURA(unitId)

Difference is in : or .


Ok, then

function Questie:OnEvent()
    Questie[event](arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10)
end

— that declaration is equivalent to

function Questie.OnEvent(self)
    local callback = Questie[event]
    callback(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10)
end

You've lost table as first argument and passed arg1 instead.
So, inside UNIT_AURA self would be unitId, and unitId would be nil
expected args = self, unitId
given args = unitId (only)

The correct call is like that:

function Questie:OnEvent()
    Questie[event](self, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10)
end

Upvotes: 2

Related Questions