lua-users home
lua-l archive

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



> That’s a very interesting idea, but I’d really like to run some cleanup code in the same coroutine when the slideshow is aborted.

Only slightly more difficult. I was going to suggest this in the first place, but the question at the end seemed relevant.

coroutine:

  local function cleanup()
    -- do stuff
  end

  register_cleanup(cleanup)

Supporting function (assumes that Wait is provided):
(This must be a Lua function, otherwise the yield in Wait won't work)

  function register_cleanup(fn)
    local _wait = Wait
    function Wait(time)
      local thrown = _wait(time)
      if thrown then  fn();  error(thrown);  end
    end
  end

Now, if (the original) Wait returns with a "true" result, the registered cleanup function will be called, and then the thread will return the result from Wait as an error result (which you can pick up from lua_resume).

There are many variations on this theme: one is to provide the thrown object to the cleanup function and let it return an error object:

  if thrown then error(fn(thrown)) end

Another option would be to allow multiple cleanup functions, perhaps by keeping a table of them.

However, what might you need to clean up which could not more reliably be handled by garbage collection?