Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

Can you pass tables in as arguments?

Asked by 10 years ago

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?

1function example(theTable)
2 
3end
4local theTable = {"Hi","Bob","ScriptingHelpers"}
5example(theTable)

If that works, I take it you could do

1function example(theTable)
2    for i = 1,#theTable do
3        print(theTable[i])
4    end
5end
6local theTable = {"Hi","Bob","ScriptingHelpers"}
7example(theTable)

2 answers

Log in to vote
6
Answered by 10 years ago

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

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

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

1function PrintArgs(...)
2    local t = {...}
3    for i = 1, #t do
4        print(t[i])
5    end
6end
7PrintArgs(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).

Ad
Log in to vote
-3
Answered by
Muoshuu 580 Moderation Voter
10 years ago

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

0
The table is formed after the function, yet the line calling the function sends the table to the function. It will work fine. M39a9am3R 3210 — 10y
0
Please explain why the hell you are down-voting before just down-voting a real answer... Muoshuu 580 — 10y

Answer this question