In Lua, a function
is used to make what is called a sub-program.
There are two types of subprogram:
Procedure
- A procedure is used to simplify code - if you have something you want to do multiple times. This is generally used if you have lots of code to group together that will be used more than twice (I’d say).
It’s a bit misleading in Lua, both types are called function
when written in code.
--This example is moving players to a part in the Workspace.
local function tpPlayers()
for _, player in ipairs(game:GetService("Players"):GetPlayers()) do
player.Character.HumanoidRootPart.CFrame = workspace.Part.CFrame
end
end
Then there’s the other type: a function. This is similar to a procedure, but returns a value.
--Addition example
local function add(numberOne, numberTwo)
return numberOne + numberTwo --return the added result to where it was requested
end
local answer = add(5, 7)
print(answer) --outputs "12"
They are more helpful in more complicated things, especially when you start using ModuleScript
s. Some events pass parameters when connected to a function or procedure, for example the Players
service’s PlayerAdded
and PlayerRemoving
, which both pass the player as the parameter. These are crucial for data saving and loading.
local players = game:GetService("Players")
local function load(player) --Parameters passed by PlayerAdded (the player joining, in this instance)
print("@"..player.Name.." has joined the game!")
end
players.PlayerAdded:Connect(load) --Invoke the function when the event fires
This example displays that the player has joined the game - the player was acquired through the parameter.
Other examples are in other events, like a part’s Touched
event.
local function onTouch(hit) --hit is the part that touched
local player = game:GetService("Players"):GetPlayerFromCharacter(hit.Parent)
if player then
print("@"..player.Name.." touched the part.")
end
end
In the two examples, parameters are crucial for the code to run. As I said earlier, they are also incredibly useful when simplifying code, where procedures and functions need to do the same thing multiple times. They slot well with variables.
Parameters can be passed to both types of subprogram. They tend to be more useful in functions (I find).
Here’s the documentation:
Functions and Events | Documentation - Roblox Creator Hub
I’ve written a lot here, someone please point out if I missed anything…