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 4 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)?

function angleInFront()
    local lookVector = script.Parent.CFrame.LookVector
    local otherVector
    local angleBetween

    for i,v in pairs(workspace:GetChildren) do
        if v.Name == "Part" then -- and other conditions
            otherVector = (v.Position - script.Parent.Position).Unit
            angleBetween = math.deg(math.acos(lookVector:Dot(otherVector)))
            if angleBetween < 90 then -- 90 degrees on either side from the front
                return angleBetween
            end
        end
    end
end

angleInFront()
print angleBetween

1 answer

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

Explanation

function angleInFront()
    local lookVector = script.Parent.CFrame.LookVector
    local otherVector
    local angleBetween

    for i,v in pairs(workspace:GetChildren) do
        if v.Name == "Part" then -- and other conditions
            otherVector = (v.Position - script.Parent.Position).Unit
            angleBetween = math.deg(math.acos(lookVector:Dot(otherVector)))
            if angleBetween < 90 then -- 90 degrees on either side from the front
                return angleBetween
            end
        end
    end
end

angleInFront()
print 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


function Onaddition(num1,num2) local result = num1 + num2 return result end local finalAnswer = Onaddition(2,2) print(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


function Onaddition(num1,num2) local result = num1 + num2 end local finalAnswer = Onaddition(2,2) print(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 — 4y
Ad

Answer this question