Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

How can I do variable number of variables (...) in a for loop?

I want to write normal code that takes a generic iterators as a parameter, and then does stuff to the values the iterator makes:

function iterator(...)
	for x in ... do
		-- do stuff
	end
end

But in general, iterators return more than one thing, e.g., next returns i, v.

Is there an elegant way to get all of the things the iterator returns, since I can't actually use ... as the variable in a for (I wish I could)?

for a, b, c, d, e, f, g, h, i, j, k, l, m in ... do
	--- blah...

1 comment

0

Solved, probably.

1 answer

✓ Accepted answer

Iterate manually.
For loops can be emulated inside of a function. Try this.

function iterator(iter, const, init)
	-- Iterator, constant, init (Nil, normally)
	local curr = {iter(const,init)};
	while curr[1] do
		-- ... is now contained inside of curr
		-- ... is equivalent to unpack(curr)
		
		-- Leave this here.
		curr = {iter(const,curr[1])};
	end;
end

This discussion is preserved as it was. New answers, comments, and votes are closed.