Skip to main content

Run code when the script is terminated

Notes

This is not a function.
It uses Lua's garbage collection mechanism to run code when the script ends (or is terminated).

Principle: define a global object (a table) and set its destructor to a function. When the Lua VM shuts down, the destructors of all Lua objects (including this one) are called. In Lua, a "destructor" is the object's __gc metamethod.

Minimal example

-- keywords: terminate callback, on-exit
SOME_VAR = {}
setmetatable(SOME_VAR, {
__gc = function(...)
sys.toast('Terminated!')
sys.msleep(500)
end
})
--
while (true) do
sys.toast("You can try terminating the script now\n\n"..os.date("%Y-%m-%d %H:%M:%S"))
sys.msleep(1000)
end

Note: Uses sys.toast, sys.msleep, setmetatable

Full helper example

function atexit(callback) -- Register a function to run when the script ends; avoid long operations here.
____atexit_guard____ = ____atexit_guard____ or {}
if type(____atexit_guard____) == 'table' then
if not getmetatable(____atexit_guard____) then
setmetatable(____atexit_guard____, {
__gc = function(self)
if type(self.callback) == 'function' then
pcall(self.callback)
end
end
})
end
____atexit_guard____.callback = callback
else
error('Do not name your variable `____atexit_guard____`.')
end
end
-- Copy the above to the top of your script; usage below
--
-- Register an on-exit callback
atexit(function()
sys.toast('Terminated!')
sys.msleep(500)
end)
--
while (true) do
sys.toast("You can try terminating the script now\n\n"..os.date("%Y-%m-%d %H:%M:%S"))
sys.msleep(1000)
end

Note: Uses sys.toast, sys.msleep, setmetatable