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

Can you pass tables in as arguments?

Just a quick question. Say I have a function, can I use tables in it's arguments?

Could a table that I defined earlier be passed in to a function?

function example(theTable)
	
end
local theTable = {"Hi","Bob","ScriptingHelpers"}
example(theTable)

If that works, I take it you could do

function example(theTable)
	for i = 1,#theTable do
		print(theTable[i])
	end
end
local theTable = {"Hi","Bob","ScriptingHelpers"}
example(theTable)

2 answers

✓ Accepted answer

You can. In fact, I don't know if there's anything you can't pass as an argument - and that includes functions! ex:

function Add1(n) return n+1 end
function Double(n) return n*2 end
function PrintN(n, Modifier)
	print(Modifier(n))
end
PrintN(5, Add1) --prints 6
PrintN(5, Double) --prints 10

You can also pass any number of arguments to a table if you use the parameter "...":

function PrintArgs(...)
	local t = {...}
	for i = 1, #t do
		print(t[i])
	end
end
PrintArgs(1, 5, "hi", "etc")

PS You can test your script very quickly by opening Roblox Studio and pasting your script into the Command Bar (you need a blank place open for it to work, and you need the Output window open to see the results).

As long as you set the variable before the function, example(), is called it should work perfectly fine.

2 comments

0

The table is formed after the function, yet the line calling the function sends the table to the function. It will work fine.

0

Please explain why the hell you are down-voting before just down-voting a real answer...

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