How to make 'return' not stop a function

I’m making an intermission system and I need to return Value - 1 each time.
How would I do so?

for i = 1,StartingNumber do
		wait(1)
		return Value - 1
	end

Maybe just set a variable? I don’t think there is a way to do it. At the top of the script you could just put:

Local value = 0

If you need to return it to another script try using an event?

I may be wrong don’t hate


image
image

You will need to give code access to the current value a different way. What you are doing currently is impossible :wink: Here are a few options:

Option 1 – Return the a table or value object that gets updated by your tick method.

function API:TickDown(StartingNumber)
   local Countdown = {Value = StartingNumber}
   -- or Instance.new("IntValue") and set the value

   -- run this code in parallel (will still run after function stops)
   spawn(function()
      -- you can count down using a for loop by setting the third parameter to a negative number 
      for Value = StartNumber, 0, -1 do
         wait(1)
         Countdown.Value = Value
      end
   end)

   return Countdown
end

-- OTHER SCRIPT --

local API = require(script.IntermissionModule)
local TickValue = API:TickDown(10)

-- if it is a value object, you can do this
TickValue.Changed:Connect(function()
    print(TickValue.Value)
end)

-- regardless, you can use the value like this and it will be up to date every time it is used
TickValue.Value

Option 2 – Give the tickdown code a function to run every tick

function API:TickDown(StartingNumber, Callback)
   -- if you want this to not stop your other code, wrap it inside spawn()
   for Value = StartingNumber, 0, -1 do
      wait(1)
      Callback(Value)
   end
end

-- OTHER SCRIPT --

local API = require(script.IntermissionModule)
API:TickDown(10, function(Value)
   print(Value)
end)

Option 3 – Return a BindableEvent (or Signal) for the script to use

function API:TickDown(StartingNumber)
   local Bindable = Instance.new("BindableEvent")

   spawn(function()
      for Value = StartNumber, 0, -1 do
         wait(1)
         Bindable:Fire(Value)
      end
   end)

   return Bindable.Event -- return a signal for ease of use
end

-- OTHER SCRIPT --

local API = require(script.IntermissionModule)
local Ticked = API:TickDown(10)

Ticked:Connect(function(Value)
   print(Value)
end)
4 Likes

Return stops the entire function at all times, unlike break which stops its loop or the function. Therefore, it’s impossible to stop return from stopping a function. You should consider the aforementioned alternatives.

1 Like

You could put them into a table and return that but @EmeraldSlash has already said that.