lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


On Sunday 06, Luiz Henrique de Figueiredo wrote:
> > In my opinion, os.exit() is for exiting quickly and letting the OS
> > worry about cleaning up.
>
> Exactly. Nevertheless, in Lua 5.2, os.exit will accept a flag that tells
> whether to close the Lua state.

How about an os.atexit(func) function to register Lua functions to called when 
os.exit() or a normal exit happens.  This way Lua scripts can still do 
resource cleanup if they need/want to.  Attached 'atexit.lua' is a simple 
pure Lua os.atexit() function, it catches both 'os.exit()' and normal exit.

Personally I am in the camp of people that like to have all memory/resources 
released by the application/daemon before it exit's back to the OS.  But for 
simple shell type scripts this is overkill.

P.S Yay for money-patching. ;)

-- 
Robert G. Jakabosky
local exit_list={}
local exit=os.exit
local function cleanup()
	-- call atexit functions in reverse order
	for x=#exit_list,1,-1 do
		local func = exit_list[x]
		func()
	end
end
-- catch normal exit.
local t=newproxy(true)
t=getmetatable(t)
t.__gc = cleanup

os.exit = function(...)
	cleanup()
	exit(...)
end
os.atexit = function(func)
	table.insert(exit_list, func)
end

require("atexit")

print("call atexit")
os.atexit(function()
	print "atexit function number 1"
end)
os.atexit(function()
	print "atexit function number 2"
end)
os.atexit(function()
	print "atexit function number 3"
end)
os.atexit(function()
	print "atexit function number 4"
end)

rc=arg[1] or nil
if rc ~= nil then
	print "call os.exit()"
	os.exit(rc)
	print "error error shouldn't get here."
end

print "normal exit no 'os.exit()' call"