I need explanation of how "return" really did on (this script)

I’ve been coding for little long. I’m trying to made a mob when they need to follow the nearest player. I get an example of how to do it and then read them. I probably know how they work, but I’m confuse with using of “return” on this script.

local CharModel = script.Parent
local Humanoid = CharModel.Humanoid

local function followNearest()
	local currentdistance = math.huge
	local target = nil
	
	for i,player in pairs(game.Players:GetPlayers()) do

		if player and player.Character ~= nil then
			local character = player.Character

			local distanceFromPlayer = (character.PrimaryPart.Position - CharModel.PrimaryPart.Position).Magnitude
			
			--print(character.Name, distanceFromPlayer)
			
			if distanceFromPlayer < currentdistance then
				currentdistance = distanceFromPlayer
				target = character
			end
			
			if target ~= nil then
				Humanoid:MoveTo(target.PrimaryPart.Position,target.PrimaryPart)
				print(target)
			end
			
			currentdistance = distanceFromPlayer
			
		end
	end
	return target -- How does this work???
end


while task.wait() do
	followNearest()
end

What I know about “returning” is it will return the value from the function. And something like

local function minute(a)
      return a * 60 
end

print(minute(2)) -- 2 * 60 = 120

But, still I don’t understand of how it works. (Since English isn’t my primary language) Any explaination is appreciated.

return will return the value that is attached to it, and also completely stop the function

its like flagging the variable and telling the function caller “hey, im all finished, here’s the result” or “hey, im all finished, ive made the nessecary changes”

1 Like

According to the script. It means that the target is already given and getting out the result until it changes smth like that?

it figures out which player is closest to it and sets the target variable to that player and returns it

1 Like

I have a question. Does return means by returning the result back to the start or just getting out the result?

it just means getting the result, in this case it doesn’t do anything with the returned value, but it gives back the result anyway in case you want to do something with that variable it has already computed

1 Like