Functions are containers of reusable code.
Say you want to print the squares of certain numbers.
You might write it like so;
for i = 1, 10 do print(i^2); end
But what if you need to do this multiple times? Don't copy and paste the same exact code.
Instead, put it in a function.
local function printSquares(start, goal) -- printSquares is just a variable that contains a reference to this function start = goal == nil and 1 or start for i = start, goal do print(i^2) end end printSquares(5); -- instead of copying the body, just copy this call with any numbers
If you will often be using something, it's best to have a variable contain it/a reference to it.
Like you might want to change a parts properties.
game.Workspace.Part.Transparency = 0.2; game.Workspace.Part.Reflectance = 0.2; game.Workspace.Part.BrickColor = BrickColor.new("Really red");
Instead have a variable refer to the part!
local part = game.Workspace.Part part.Transparency = 0.2; part.Reflectance = 0.2; part.BrickColor = BrickColor.new("Really red");
But actually use
part! There's many cases where one declares a variable, but never uses it and just indexes the game and its descendants until a certain child is reached, despite having a variable for it
Say you want to do something a certain amount of times, it would be tedious to just copy the code the amount of times you want to do something, that is where loops come in.
-- Instead of manually calling printSquares 10 times for i = 1, 10 do printSquares(i, i); end -- And if you want to do something forever while true do part.BrickColor = BrickColor.Random(); wait(0.1); end