Functions allow for you to "package" snippets of code that you use in your scripts and call them later. They also allow you to perform operations on an input and return an output. Finally, they also allow you to receive an input and perform certain things based on the input. Arguments, also called parameters, allow you to pass values to a function that it can then use to produce a different result or give a different output.

Arguments are very similar to local variables created when you call the function:

function NAME(Argument1,Argument2,Argument3,etc)

The body of the function is where the action takes place, it contains the code that will be ran when the function is called. It can access the arguments passed to it under the names defined in the function's argument list.

Any code you want to run when the function is called must go in the function body.

function NAME()
--Function body
--End of function body
NAME() -- 4

Any return statement put into the function will instantly stop the function and return all the values following it.

function func()
return 2 --The function ends here
print("This will never be printed because we already returned.")

Functions, like all the other control structures except the repeat structure end with the 'end' keyword.

Any amount of arguments

Sometimes, you may need a function that can accept any amount of arguments. You would do this by using this code.

function func(...)
local args = {...}

Now, 'args' is defined as a table, which contains all the arguments given.

Community content is available under CC-BY-SA unless otherwise noted.