Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

Is there a proper way to stop a function?

Asked by 5 years ago

Is there a way to stop a function, outside of a function? Something like this.

local hum = game.Players.LocalPlayer.Character.Humanoid

function fish()
    print("yes")
    wait(1)
    print("no")
    wait(1)
    print("yes")
    wait(1)
    print("no")
end)

spawn(function()
    fish()
end)

hum.Died:connect(function()
    fish:stop() -- ??
end)

This script is an example. ;-;

0
Try looking at coroutines. https://www.lua.org/pil/9.1.html EpicMetatableMoment 1444 — 5y
0
You can use `spawn(fish)` if fish takes no arguments User#26471 0 — 5y

1 answer

Log in to vote
0
Answered by 5 years ago
Edited by User#26471 5 years ago

Something like:

local player = game:GetService('Players').LocalPlayer
local char = player.Character or player.CharacterAdded:Wait()
local hum = char:FindFirstChildWhichIsA('Humanoid')

function startFish()
    local stop = false

    spawn(function()
        if stop then return end
        print('yes')
        wait(1)
        if stop then return end
        print('no')
        wait(1)
        if stop then return end
        print('yes')
        wait(1)
        if stop then return end
        print('no')
    end)

    return function() stop = true end
end

local stopFish = startFish()

hum.Died:connect(stopFish)

Explanation:

  • We use a "startFish" function that spawns and returns semi-immediately (yielding until the function is completed for something that lets us stop it in the middle is a bit useless)
  • Inside, we have a local variable inside that function that tells that particular instance to stop
  • Lots of checks inside the spawned function (waits are harmless, I strongly recommend putting the "breakpoints" right before the actions rather than before the waits)
  • startFish returns a function you can use to ensure no other things are printed

c:

Ad

Answer this question