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 9 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?

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

Log in to vote
6
Answered by 9 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:

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).

Ad
Log in to vote
-3
Answered by
Muoshuu 580 Moderation Voter
9 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 — 9y
0
Please explain why the hell you are down-voting before just down-voting a real answer... Muoshuu 580 — 9y

Answer this question