Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

How do I use return to return values?

Asked by 5 years ago

Lets say I have a function that runs through conditions, and if those conditions are met, it will return a value to be printed. In this case it is a function that checks the angle between two objects, like so:

(It returns nil. What's wrong with the script and how do I use return properly)?

01function angleInFront()
02    local lookVector = script.Parent.CFrame.LookVector
03    local otherVector
04    local angleBetween
05 
06    for i,v in pairs(workspace:GetChildren) do
07        if v.Name == "Part" then -- and other conditions
08            otherVector = (v.Position - script.Parent.Position).Unit
09            angleBetween = math.deg(math.acos(lookVector:Dot(otherVector)))
10            if angleBetween < 90 then -- 90 degrees on either side from the front
11                return angleBetween
12            end
13        end
14    end
15end
16 
17angleInFront()
18print angleBetween

1 answer

Log in to vote
1
Answered by 5 years ago
Edited 5 years ago

Explanation

01function angleInFront()
02    local lookVector = script.Parent.CFrame.LookVector
03    local otherVector
04    local angleBetween
05 
06    for i,v in pairs(workspace:GetChildren) do
07        if v.Name == "Part" then -- and other conditions
08            otherVector = (v.Position - script.Parent.Position).Unit
09            angleBetween = math.deg(math.acos(lookVector:Dot(otherVector)))
10            if angleBetween < 90 then -- 90 degrees on either side from the front
11                return angleBetween
12            end
13        end
14    end
15end
16 
17angleInFront()
18print angleBetween

It is supposed to return a nil value because obviously, you haven't defined the variable in line 04 which is actually fine.

Returning is the act of sending certain information back to where the function was called from..

Example 1

1function Onaddition(num1,num2)
2    local result = num1 + num2
3        return result
4end
5 
6local finalAnswer = Onaddition(2,2)
7 
8 
9print(finalAnswer)

The output prints 4.

Let's say if you remove the return result from the code. The output would print nilbecause returning can be also used for later purposes like storing something that you want to use for later purposes.

Example 2

1function Onaddition(num1,num2)
2    local result = num1 + num2
3end
4 
5local finalAnswer = Onaddition(2,2)
6 
7 
8print(finalAnswer)

The output prints nil because there is no return result in the code. I hope this helps you how to use return properly and please up vote this answer if it has helped you..

0
This does help, thank you. radiant_Light203 1166 — 5y
Ad

Answer this question