Function with variable number of arguments

Post Reply
naftali
Posts: 138
Joined: Wed Jan 20, 2010 8:42 pm

Function with variable number of arguments

Post by naftali »

A fairly simple question, with perhaps a not-so-simple answer. Lets say I want to make a targeting function that looked like the following:

Code: Select all

function tar( tar1, tar2, tar3..., tarn, tf )
	targets[1] = ( tar1 or targets[1] )
	targets[2] = ( tar2 or targets[2] )
	targets[3] = ( tar3 or targets[3] )
...
	targets[n] = ( tarn or targets[n] )
	if tf ~= false then
		echo("Targeting " .. targets[1] .. " and " .. targets[2] .. " and " .. targets[3] .. "\n")
	end
end
To clarify, I would only want to echo the first 3 targets, not all of them. And the 'tf' argument at the end to give the option of whether or not to echo the targets would be nice, but isn't necessary. Is there a way that I could do this?

Denarii
Posts: 111
Joined: Thu Dec 03, 2009 10:54 pm

Re: Function with variable number of arguments

Post by Denarii »

Code: [show] | [select all] lua
function tar(...)
	targets = {...}
	if targets[1] == nil then return end
	if targets[#targets] ~= false then
		echo("Targeting: " .. targets[1])
		if #targets > 1 then
			for i=2, #targets do 
				if i > 3 then echo("\n"); return end
				echo(" and "..targets[i])
			end
			echo("\n")
		end
	end
end

naftali
Posts: 138
Joined: Wed Jan 20, 2010 8:42 pm

Re: Function with variable number of arguments

Post by naftali »

wow, that's awesome! Is there a way to make an alias so that it would feed the correct arguments in? So an alias where typing 't me you sam sue' would do tar('me', 'you', 'sam', 'sue')?

Denarii
Posts: 111
Joined: Thu Dec 03, 2009 10:54 pm

Re: Function with variable number of arguments

Post by Denarii »

I don't know what characters you want to accept for valid targets, so I went with alphanumeric.

Code: Select all

^t(?: ([a-zA-Z0-9]+))+$

tar(unpack(matches, 2))

Post Reply