A function is a procedure. You take things in, do stuff, and put things out. There is a function definition where you say how it works. That will decide which parameters you take in.
Looking at documentation
Reading documentation is very important to programmers!
If you want to know a function built into ROBLOX, you can look at the Wiki.
For example, you can look at the documentation for table.insert.
table.insert(table, [pos,] value) tells you how to use it. The first parameter is table, the second parameter (which is optional -- that's what the [] mean) is the position, and the third parameter is the value.
The description below tells you what it does and how to use it:
Inserts element value at position pos in table, shifting up other elements to open space, if necessary. The default value for pos is n+1, where n is the length of the table (see §2.5.5), so that a call table.insert(t,x) inserts x at the end of table t.
And it includes example code.
Methods
Methods are functions that act on a particular object. They usually use : instead of .. You can look up the methods available on the type of object from the Wiki. For example, we can look up what a Player has.
We can see the following line under "Functions":
void Kick ( string message = "" )
Removes a player from the game by disconnecting their client.
And you can click "Kick" to get a more detailed view.
void Kick( string message = "" )
This tells you it returns void (nothing), it takes in a string called message, which defaults to "" (empty text).
Defining Functions
When you define a function, you give it the block of code it executes:
function sayHi()
print("Hello")
end
sayHi()
If your function needs some information to decide what to do, it can take in parameters. You put the names of the parameters in the (), and then those variables can be used in the body of the function:
function sayHiTo(person)
print("Hello", person)
end
sayHi("BlueTaslem")
When you call the function (use it), you line up the parameters in the function definition with the values going in.
For example, in
function add(a, b, c)
return a + b + c
end
print( add(1, 2, 3) )
a is 1; b is 2; c is 3.
Normally, the number of parameters in the function definition and where you call it will be the same.
If you provide more arguments than the function defined, they are ignored:
function add(a, b)
return a + b
end
print( add(5, 1, "cat") )
If you provide fewer, they are nil in the body of the function:
sayHiTo()
This can be useful for making "optional" parameters:
function sayHiTo(person)
if person == nil then
print("Hello Bob")
else
print("Hello", person)
end
end
sayHiTo()