Hey guys. I’m having a bit of trouble with returning. I’m currently revising and making a big notes page for Roblox Scripting because I personally want to develop a couple of games. But I’m stuck on returning. It would be greatly appreciated if yous could help me out with what returning is seeing im a beginner.
local function hi()
print(“hi”)
return “Awesome”
end
local Chicken = hi()
print(Chicken)
Here’s a beginner script that I had. I understand it partially but it is quite confusing why it will return ‘Awesome’ here but not in here
local function hi()
print(“hi”)
return “Awesome”
end
hi()
I’ve looked on the Roblox Developer website but there is literally no explanations to returning which is kind of weird to me. There are links to other explanations but there obviously not made for beginners like me.
Any help is appreciated thanks!
return is a Lua statement that lets you grab an instance or value from a function when it is called.
A common use of return is making functions for basic arithmetic functions like this:
function add(a, b)
return a + b
end
local result = add(5, 10)
print(result) -- 15
You can use it to fetch a processed part in a function for further alteration:
function newPart()
local part = Instance.new("Part")
part.Parent = workspace
return part
end
local p = newPart()
p.BrickColor = BrickColor.new("Really red")
Both scripts you have are fine, but for the 2nd one where you assume nothing is returned, it returns it, but it’s because you didn’t assign the return value to a variable. If you assign it to a variable and print that variable, it’d print ‘Awesome’
I think a simple way to look at it is, you give a function and input and it returns something as an output. Some functions don’t require an input but can still output something to tell you what you like to know.
For example, if I make a function Add(x, y), I expect it to return x + y.
You can use returning for other things; for example, if I have a function MoveCharacter() that has a preset movement (no input), I would still like to know if the function actually moved the player. So if I made it return true if it worked, then the script can tell if it moved. If it returned false, then that means something messed up the character movement.