WoWInterface

WoWInterface (https://www.wowinterface.com/forums/index.php)
-   Lua/XML Help (https://www.wowinterface.com/forums/forumdisplay.php?f=16)
-   -   Code to Convert a Table to a List (for lack of better terms) (https://www.wowinterface.com/forums/showthread.php?t=34668)

Sapu94 08-28-10 02:16 PM

Code to Convert a Table to a List (for lack of better terms)
 
So here is my situation for my addon. Here is a function very similar to one I have:

Code:

function testFunction(parent, index, ...)
        return tableOfFunctions[index](parent, ...)
end

A call to this function would look like:

Code:

local i = object:testFunction(index, param1, param2, param3)
however the function can be called with anywhere from 1 parameter (just the index) to 6 parameters (index + 5 other parameters). This all works just fine but what I want to do is to be able to call the function like this:

Code:

local paramTable = {index, param1, ...}
local i = object:testFunction(paramTable)

Essentially I am passing just one parameter (a table) and I need some code to put into testFunction() that will then split up that table into individual parameters and pass the correct ones onto tableOfFunctions[index](...).


Is there any better way of doing this than to just get the length of the table and then have an if statement for every number of parameters like this?:

Code:

function testFunction(pTable)
        local length = #(pTable)
        if length == 2 then
                tableOfFunction[pTable[2]](pTable[1])
        elseif length == 3 then
                tableOfFunction[pTable[2]](pTable[1], pTable[3])
        elseif length == 4 then
                tableOfFunction[pTable[2]](pTable[1], pTable[3], pTable[4])
        elseif length == 5 then
                tableOfFunction[pTable[2]](pTable[1], pTable[3], pTable[4], pTable[5])
        elseif length == 6 then
                tableOfFunction[pTable[2]](pTable[1], pTable[3], pTable[4], pTable[5], pTable[6])
        elseif length == 7 then
                tableOfFunction[pTable[2]](pTable[1], pTable[3], pTable[4], pTable[5], pTable[6], pTable[7])
        end
end

I realize that that solution would work just fine but I am still curious if there is a better way of doing it as I enjoy learning new programming tricks :).

Thanks

d87 08-28-10 03:07 PM

local a,b,c,d = unpack(pTable)
tableOfFunction[b](a,c,d)

also you can unpack at the point when you call testFunction
testFunction(unpack(pTable))

Sapu94 08-28-10 04:56 PM

unpack is just what i was looking for!

I actually ended up working around having to do it but learning new lua functions is never a bad thing :)

Thanks


All times are GMT -6. The time now is 12:53 PM.

vBulletin © 2024, Jelsoft Enterprises Ltd
© 2004 - 2022 MMOUI