lua-users home
lua-l archive

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


On Wednesday 11, Josh Haberman wrote:
> On Wed, Apr 11, 2012 at 6:07 AM, Roberto Ierusalimschy
> 
> <roberto@inf.puc-rio.br> wrote:
> > It does not seem a good practice to create new resources when finalizing
> > something, and it can easily create an infinite loop. So, to avoid
> > infinite loops, Lua does not call the finalizers of objects created
> > after the call to lua_close.
> 
> I see.  In that case, using finalizers to implement a Lua-level
> atexit() doesn't seem like a viable technique.
> 
> https://github.com/dcurrie/lunit/blob/master/atexit.lua
> 
> Is there any other way to accomplish this?

local actions = {}
local function do_actions()
  local i = 1
  while true do
    local cb = actions[i]
    if not cb then break end
    cb()
    i = i + 1
  end
end

if _VERSION >= "Lua 5.2" then
  setmetatable(actions, {__gc = do_actions})
else
  local canary = newproxy(true)
  local meta = getmetatable(canary)
  meta.__gc = do_actions
  -- keep canary alive
  actions.canary = canary
end

function atexit(fn)
  actions[#actions + 1] = fn
end

-- 
Robert G. Jakabosky