Thread Tools Display Modes
08-28-10, 02:16 PM   #1
Sapu94
A Murloc Raider
AddOn Author - Click to view addons
Join Date: Feb 2010
Posts: 6
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
  Reply With Quote
08-28-10, 03:07 PM   #2
d87
A Chromatic Dragonspawn
 
d87's Avatar
AddOn Author - Click to view addons
Join Date: Jan 2006
Posts: 163
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))

Last edited by d87 : 08-28-10 at 03:15 PM.
  Reply With Quote
08-28-10, 04:56 PM   #3
Sapu94
A Murloc Raider
AddOn Author - Click to view addons
Join Date: Feb 2010
Posts: 6
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
  Reply With Quote

WoWInterface » Developer Discussions » Lua/XML Help » Code to Convert a Table to a List (for lack of better terms)


Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off