pass the contents of an indexed table to a function

Post Reply
Caled
Posts: 403
Joined: Thu Apr 09, 2009 4:45 am

pass the contents of an indexed table to a function

Post by Caled »

The following demo script almost works. That is to say that if you run demo.startfunc("att1"), the following is displayed in the main window:
Startfunc is calling function: att1
endfunc says hello and knows:
- a
- b
The point of fail is that rather than passing the arguments to demo.endfunc directly, I want to dynamically pass them from the contents of another variable - in this case demo.arglist

func(arglist) doesn't work, obviously. Is there a way?
Code: [show] | [select all] lua
demo = {}
demo.arglist = {"a", "b", "c"}
demo.funclist = {}

demo.startfunc = function( att )
	echo("\nStartfunc is calling function: " .. att)
	local func = demo.funclist[att]
	local arglist = demo.arglist
	
	func("a", "b")

end

demo.endfunc = function( ... )
	echo("\n endfunc says hello and knows: \n")
	local arglist = {...}
	for _,a in ipairs(arglist) do	
		echo("    - " .. a .. "\n")
	end
end

demo.funclist = {
	att1 = demo.endfunc,
}

demo.startfunc("att1")

User avatar
Vadi
Posts: 5042
Joined: Sat Mar 14, 2009 3:13 pm

Re: pass the contents of an indexed table to a function

Post by Vadi »

Code: [show] | [select all] lua
unpack(demo.arglist)
?

Jor'Mox
Posts: 1146
Joined: Wed Apr 03, 2013 2:19 am

Re: pass the contents of an indexed table to a function

Post by Jor'Mox »

Or you could try this:
Code: [show] | [select all] lua
local arglist
if type(arg[1]) == "table" then
	arglist = arg[1]
else
	arglist = arg
	arglist.n = nil
end
Then you can either pass individual variables, or a table of them, and they will be captured in either case.
Of course, if you want to pass normal variables and a table of variables, then it could get complicated, though then you could just use: arglist = arg and it should be fine, since it is not essentially different from using: arglist = {...} except that the arg variable also contains the index "n" which holds the number of arguments it has been passed.

Post Reply