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

What are Functions?

I know they look like this:

function onTouch(part)

end

but I have no idea how to use them or what they're ment to be used for. All I know is that I need them to get better at scripting. So if you could go indepth and explain them it would help a lot. (Not dat weird animal 'alot')

(PS: I looked on the wiki and got confused. So even more dumbed down than that please ;) )

4 answers

✓ Accepted answer

Functions are blocks of code (think of them as areas of code) that run when you call them, or when an event happens. They are extremely useful for running things multiple times. Here are a few examples:

function sayHi()
	print("Hello!")
end

sayHi() --this is called 'calling' the function.  To call a function, type the name followed by ()
>>Hello!

Functions can also take parameters (AKA arguments) which go inside the (). Here is an example:

function add(a, b) --this function takes two parameters: a and b
	print(a + b) --a and b are then added together and printed out
end

add(5, 10) --call the add function.  Use 5 and 10 as the parameters.
>>15

Lastly, functions can return values. You can use this to set variables to the called function. This sounds confusing, but it's really simple. Here is what I mean:

function multiply(a, b) --take two parameters
	return a * b --return a multiplied by b.
end

local product = multiply(5, 10) --set 'product' to the return value of multiply
print(product)
>>50

A function is used rather than writing a block of code over and over again. The way you use them is like this:

function funcName(arguments)
--code
end
event:connect(funcName)

So an onTouch script would look something like this:

function onTouch(hit)
if hit.Parent:findFirstChild("Humanoid") then
print("Hi")
end
end
script.Parent.Touched:connect(onTouch)
--Touched is the event that triggers the function onTouch().

They're a way of accessing the event fired when a certain thing in-game happens. Say you touch a brick. the event fired here is the 'Touched' event. You can use the function in a script so that whenever the brick is touched it gets the event and makes something specific happen, such as deleting whatever touched it.

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