Introduction
Hello! I made a simple module that instantly fires a binded function when the script execution has exhausted. Useful for detecting when the script is destroyed or disabled. Similar functionality of game:BindToClose()
but for scripts
Use cases
- This module helps you manage memory disconnection if that ever matters to you.
- Automatically disconnects custom OOP objects that requires manual disconnection.
- Destroying associated Instances created from the script after it dies.
- I can’t think of anything else lol.
Code example
local DisconnectUtil = require(script.DisconnectUtil)
DisconnectUtil:BindToExhaustion(function()
print("This script is no longer running")
end)
print("Script is now running")
--> Disconnecting BindToExhaustion
local Thing = DisconnectUtil:BindToExhaustion(function()
print("This will never run wahhhh")
end)
Thing:Disconnect()
How does it work?
It relies on RunService.Stepped
and counting comparison. Naturally, the RunService.Stepped
automatically disconnects when the script gets destroyed or disabled.
The main module will constantly increment the StateId
for every RunService.Stepped
event.
When you use :BindToExhaustion()
it will create a new coroutine thread from the current script environment. Its job is to constantly sync with the module’s StateId
with RunService.Stepped
When the script dies from where you used the :BindToExhaustion()
. It stops counting the StateId
. Then the main module script detects that and then calls the binded function immediately.
Get this module
This is my first time creating a community resource in this forum :3