#Returning

153 messages · Page 1 of 1 (latest)

wicked cargo
#

check this

trim ocean
#

If you dont wanna read alot;

The return keyword in Luau is used to give a value back to where the functions are called. It has 2 properties:
• First of all it stops the function and no other code after the return key will be executed.
• it can return any value to the caller. Lets look at a code example:

function doMath(a, b)
return a+b
end

print(doMath(1, 2))
hasty jayBOT
#
Program Output
3

trim ocean
#

That is the output of the code ^^^

#

It can also be used to keep code from being nested, for example whenever i do anything using UserInputService.InputBegan i do this:

local UIS = game:GetService("UserInputService")

UIS.InputBegan:Connect(function(input, gpe) 
if gpe then return print("Yea this will never print so its kinda useless") end 

end)
true lion
#

i think returning is only for functions.

unreal depot
#

No, actually

#

You can use the return keyword in a script in the global scope

#

That will just keep it from running

#

What return does is it stops the execution of a function

#

So any code after that won't be run

#

And it returns a value to the caller

#

No

#

"return"

#

Is the same as "return nil"

#

So you are actually returning something, which is essentially nothing

#

Alr

#

Yes

#

Except really they're the same thing

#

Yes these are the two cases you can use it for

#

What do you mean?

#

Anything. Literally anything.

#

I'll give an example

#

Say you're writing some sort of physics system

#

And there's a equation to get the gravity that should be applied to an object

#

You need this code multiple times, not just once, so you make a function

#

That function would take the object as an input, and give you back (return) the gravity that should be applied to it

small oak
#

Good example for returning are module scripts

#

Modules are nice for omptimizing your game

#

hey

#

yeah

#

functions cannot be local

#

just get rid of the local keyword before the function and it should work

#

Module:


function module.new()
    print('Hello')
end

return module```

Script:

```local module = require(script.ModuleScript)

module.new()```
#

yeah

#

its because you are putting the function in the module table

#

you are setting functions parent to the module table

#

if you put the function before that module table variable, the script does not know what ''module'' is

#

yeah but module.new() is way easier

radiant sluiceBOT
#

studio** You are now Level 3! **studio

small oak
#

and you can access it later in the script

#

wait let me try it

#

I don't think theres anything in the table before you even put something in it

#

Prints nil because the table isn't an array

#

you would have to do print(module['idk'])

#

cuz you are naming the functions so it becomes dictionary

#

You can't access the function later in the script like this

#

wait let me show you an example

unreal depot
#

arrays are numeric, meaning they look like this:
{
[1] = some value,
[2] = some value, etc.
} and you get values like this: mytable[1]

#

dictionaries are what modules are

#

basically, saying ```lua
function module.idk()

end
is the same as sayinglua
module.idk = function()

end```

unreal depot
#

what no

#

what

#

returning is only when you need to make a variable that the function resturns

small oak
#

Example for returning:


local mouse = UserInputService:GetMouseLocation()
local mouseRay = camera:ViewportPointToRay(mouse.X, mouse.Y)

local params = RaycastParams.new()
params.FilterType = Enum.RaycastFilterType.Exclude
params.FilterDescendantsInstances = {player.Character, camera, blockGhost}

local result = workspace:Raycast(mouseRay.Origin, mouseRay.Direction * 70, params)
if result then
        return result.Position    
end
end```
small oak
#

You don't want to print it

unreal depot
#

because then u cant use the position

#

for other stuff

#

no

#

why would u print it

small oak
#

OOP would be a really good example for returning

unreal depot
#

stop bro

#

they have no clue what that even is

#

stop

#

its way too advanced

#

no

small oak
#

No i was joking don't worry about that

unreal depot
#

kinda

#

lets not get into that

small oak
#
    return a + b
end

returnResult(5, 5) --> 10```
small oak
radiant sluiceBOT
#

studio** You are now Level 9! **studio

unreal depot
#

u cant

#

because thats a connection

#

not a function

small oak
#

yeah

unreal depot
#

because u cant get the result from there

small oak
#

You'd do

local function getPos()
end

#

oh sorry

#

didnt mean to send

trim ocean
small oak
#

nvm

trim ocean
#

another example of returning is module scripts. A module script can return data, but only one value. Most modules return a table of contents like functions and such. Whenever another script uses the require() function and put the path to the module as the argument, they get the returned value of the module script.

trim ocean
#

anything partocular you didnt understand?

trim ocean
#

The return key would stop the execution of the rest of the code, but mo

#

no value is recieved by anything

#

also you cannot just multiply an instance

hasty jayBOT
#
Program Output
/opt/wandbox/lua-5.4.3/bin/lua: prog.lua:1: attempt to index a nil value (global 'game')
stack traceback:
prog.lua:1: in main chunk
[C]: in ?

trim ocean
#

Oh i did position

#

that doesnt work since its Luau u typed in and its lua it executes in

#

The rest of the code in the function

#

which is nothing

small oak
#

Simply. Let's say you have a function called addNumbers() like this:

    
end```

Then you wan't to set the parameters value to 1 like this:

```local function addNumbers(numberOne)
    numberOne = 1
end```

After that you wan't to assign the value of the parameter to the function name. That's where returning comes in. 

```local function addNumbers(numberOne)
    numberOne = 1
    return numberOne
end```

After that's done make a variable for the function so you can print it:

```local function addNumbers(numberOne)
    numberOne = 1
    return numberOne
end

local addNumbersFunc = addNumbers()

print(addNumbersFunc)```
trim ocean
#

for example:

local function getHeight(x, y, seed)
  local frequency = 3
  local Smoothnes = 100

  return math.noise(x / Smoothnes * freqeuncy, y / Smoothnes * frequency, seed)
end
``` this is a function to get a perlin noise value i used at specific coordinates, so instead of calculating every time i needed the height, i’d just call this function.
#

if i were to add a line after the return line it would never run

small oak
trim ocean
#

lets try to write a lua script for that:

local function MultiplyNumbers(a, b)
  return a * b
  print("Returned the multiplied numbers!")
end

print(MultiplyNumbers(10, 54))
hasty jayBOT
#
Program Output
/opt/wandbox/lua-5.4.3/bin/lua: prog.lua:3: 'end' expected (to close 'function' at line 1) near 'print'

trim ocean
#

idk why that has an error lol

#

lua cant handle code after a return key? That seems kinda weird

small oak
#

Also you can manipulate it. For example you can add numbers to it:

    numberOne = 1
    return numberOne
end

local addNumbersFunc = addNumbers() + 3  -- Added number 3 to the functions value


print(addNumbersFunc) -->  4```
trim ocean
#

no need for a function to do that

#

no not for that

#

have you not learned anything.

#

?

small oak
#

best way I could explain

hasty jayBOT
#
small oak
#

yeah

radiant sluiceBOT
#

studio** You are now Level 4! **studio

unreal depot
#

finally a good example from you

trim ocean
#

try this:

game.Players.PlayerAdded:Connect(function(plr)
    plr.CharacterAdded:Connect(function(character)
        local HRootPart = character:FindFirstChild("HumanoidRootPart")
        local function ChangePosition(RootPart)
            return RootPart.Position + (RootPart.CFrame.lookVector * 10)
        end
        
        task.wait(10)
        
        local Result = ChangePosition(HRootPart)
        print(Result)
    end)
end)
#

however youre never setting the primary parts position

#

return functions are mostly used to do calculations and return the result.

#

idk, not nescesary

#

i feel like its more organised however

small oak
#

Do you have an example

#

Array

#

thats array

trim ocean
#

[] tries to find a component of the instance or object you use [] on. Its commonly refered to as ‘indexing’. Bascly lets say you have a part in workspace called ‘Part’ then there is 2 ways of getting it:

workspace["Part"]
or
workspace.Part
#

i didnt mean to send it that early

#

well its nescesary if youre trying to find a component of an object or a value that you dont know the name of.

local myFruits = {"Apple", "Banana"}
local myFruitsPrices = {["Apple"] = 10, ["Banana"] = 4}

function getPrice(fruit)
  return myFruitsPrices[fruit]
end

for i, fruit in pairs(myFruits) do
  print(getPrice(fruit))
end
#

dictionairy, not array

#

yea cuz its a dictionairy not an array

hasty jayBOT
#
Program Output
10
4

trim ocean
#

basicly an aw

#

whoops

#

lemme try again

#

basicly an array is a dictionary but the key is numbers depending on their position in the array. These 2 are equal:

local array = {"Value1", "Value2"}
local dictionary = {[1] = "Value1", [2] = "Value2"}
#

gosh i give up

#

gl

#

i cant handle it anymore you wont listen and wont learn

#

even the biggest supercomputer would crash running that script, its a loop trying to do unlimited calculations every single frame

hasty jayBOT
#
Program Output
12.5
25
50
100

trim ocean
#

Very good! You understood return too

trim ocean
#

No, return gives the value back to where you gave it the parameter, the place where it says the function name and then the parantheses, not at the line you create the function but further down in the script.

#

Whenever you run the function

unreal depot
#

What the fuck no

#

Ok you're obviously struggling a shit ton with something as simple as functions

#

I recommend you go learn Java

#

It's a lot more beginner friendly and will teach you essentials like this

trim ocean
unreal depot
#

It forces you to learn types, functions, and oop

unreal depot