Skip to main content

Register exit callback (register_atexit)

Signature

original_callback = register_atexit(name, callback)

Parameters

  • name
    String, required. Identifier for the registered callback; reusing the same name replaces the existing one.
  • callback
    Function, required. The function to run when the script exits; keep it fast and safe to call multiple times. Pass nil to unregister the callback for this name.

Returns

  • original_callback
    Function. The previous callback registered under the same name. Returns nil if none existed, which you can use to restore the old callback if needed.

Description

Callbacks registered with register_atexit run when the script exits, including when the user stops it with the volume buttons, and they execute before Lua performs garbage collection.
Callbacks registered under different names have no guaranteed execution order; if you need ordered execution, orchestrate it inside a single callback.
Keep callback work short to avoid delaying the exit experience.
This function is available only in versions released after 2025-07-05.

Example

register_atexit("cleanup", function()
sys.toast("Clean up resources before exit")
sys.msleep(300)
end)

while true do
sys.toast("Try stopping the script with the volume key\n" .. os.date("%Y-%m-%d %H:%M:%S"))
sys.msleep(1000)
end

Note: Uses sys.toast, sys.msleep