#Returning
153 messages · Page 1 of 1 (latest)
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))
;compile
Program Output
3
mrjamp | lua | lua-5.4.3 | wandbox.org
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)
i think returning is only for functions.
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
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
** You are now Level 3! **
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
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```
you could, but it would be at some numeric index
what no
what
returning is only when you need to make a variable that the function resturns
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```
that's way too advanced
You don't want to print it
OOP would be a really good example for returning
No i was joking don't worry about that
return a + b
end
returnResult(5, 5) --> 10```
simpliest example you can think of
** You are now Level 9! **
yeah
because u cant get the result from there
nvm
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.
Yeah already explained to him
anything partocular you didnt understand?
sorry didnt see
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
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 ?
notc0ld | lua | lua-5.4.3 | wandbox.org
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
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)```
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
Forgot to mention. The output would be 1
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))
;compile
Program Output
/opt/wandbox/lua-5.4.3/bin/lua: prog.lua:3: 'end' expected (to close 'function' at line 1) near 'print'
mrjamp | lua | lua-5.4.3 | wandbox.org
idk why that has an error lol
lua cant handle code after a return key? That seems kinda weird
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```
no need for a function to do that
no not for that
have you not learned anything.
?
have you read this
best way I could explain
notc0ld | lua | lua-5.4.3 | wandbox.org
yeah
** You are now Level 4! **
finally a good example from you
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
[] 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
;compile
Program Output
10
4
mrjamp | lua | lua-5.4.3 | wandbox.org
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
Program Output
12.5
25
50
100
notc0ld | lua | lua-5.4.3 | wandbox.org
Very good! You understood return too
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
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
Is Java better than Lua for beginners? I might go ahead and try to learn that at sum point
It 100% is
It forces you to learn types, functions, and oop
I also learned Lua first but I struggled a lot with types and especially arrays