Hi everyone, I just started using module scripts and I've gotten pretty far with it, but I have a problem with using return.

part of the function that uses return:

local selectRoute = function(train, model)
	local route = train.PrimaryPart.Values.RouteValue.Value
	local given = model:FindFirstChild("GivenPath")
	
	local greenLitPaths = {}
	local yellowLitPaths = {}
	
--------omitted many lines of code
	
	local function findBestPath()
		searchPathOptions()
		if #greenLitPaths == 1 then
			local array = greenLitPaths[1]
			print(array[1])
			return array[1]
		elseif #greenLitPaths > 1 then 
			sort(greenLitPaths)
			local array = greenLitPaths[1]
			print(array[1])
			return array[1]
		elseif #greenLitPaths < 1 then
			if #yellowLitPaths == 1 then
				local array = yellowLitPaths[1]
				print(array[1])
				return array[1]
			elseif #yellowLitPaths > 1 then
				sort(yellowLitPaths)
				local array = yellowLitPaths[1]
				print(array[1])
				return array[1]
			end
		end
		resetTables()
	end
	
	if given ~= nil then
		if given.Values.BlockingTrain.Value == nil then
			findBestPath()
		end
	else
		findBestPath()
	end
	
end

function that uses selectRoute:

module.initiateChoice = function(train, model)
	local chooseRoute = selectRoute(train, model)
	print(chooseRoute)
	repeat 
		wait()
	until chooseRoute ~= nil
		local affected = chooseRoute:FindFirstChild("AffectedPaths")
		local light = model.Values.Light.Value
		local status = model.Values.Status
		status.Value = chooseRoute.Values.Status.Value
		switchMod.setSwitches(chooseRoute.Switches)
		light.TrackDisplay.SurfaceGui.TextLabel.Text = chooseRoute.Values.ToTrack.Value
		module.exist(affected, function(object)
		module.alertAffected(train, object)
		end)
end

I noticed that selectRoute prints an existing object when it's called, but printing chooseRoute puts "nil" in the output. Unless I'm mistaken, these are the exact same things, but they have different outputs. Can someone explain this?

By the way, I know it's super long, but if I can solve this problem then I will make a huge step towards completing my concept.