Why do we use function and return on script?

Hi, I’m learning Luau but when I learn something I’m asking to myself “Why am I learning this thing?” And I didn’t understand why are we using functions, scope and return? Can you give me some simple examples?

1 Like

A function is supposed to perform a repeatable operation and is designed to provide a response:

local animals = {"cat","dog","horse"}

local function notCat(checkAnimal)
   if checkAnimal == "cat" then
      checkAnimal = "dog"
   end
   return checkAnimal
end

while true do -- loop endlessly
   local animal = animals [math.random(1, #animals)] -- choose a random animal
   print(animal)  -- shows what we first set
   notCat(animal ) -- check and change via function
   print(animal)  -- what it is now
   task.wait()
end

Obviously they do far more complex things than that, but as a basic example, does it make sense?

For better examples, check out the official Roblox Education site on functions:

2 Likes

(edit) This helped me so much and I will ask a question. If you use return code Is It turning back when It finishes the code?

1 Like

At any point that you issue a return, it will exit the function go back to where first called it.

2 Likes

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.