Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

How do I use return to return values?

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

✓ Accepted answer

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..

1 comment

0

This does help, thank you.

This discussion is preserved as it was. New answers, comments, and votes are closed.