lua-users home
lua-l archive

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


Glenn Maynard <glenn <at> zewt.org> writes:

> I think Lua's GC scheme isn't capable of actually implementing dtors
> efficiently, but how do people deal with this?

If your critical objects are only alive within a well-defined scope
(and ideally, they usually should be), a functional approach
works well.

Instead of:

  local file = io.open("myfile", "w")
  file:write("Quick brown fox.")
  file:close()

Do this instead:

  callWithFile("myfile", "w", function (file)
    file:write("Quick brown fox.")
  end)

Where the higher-order function might be defined as:

  function callWithFile (filename,mode,func)
    local file = io.open(filename, mode)
    local ok, err = pcall(func,file)
    if file then file:close() end
    if not ok then error(err) end
  end

Notice that, in the case of exceptions, this cleans up the resource
and then propagates the exception.

If you have a lot of resources like this (mutexes, network connections,
whatever), you can abstract out the pattern:

  function callWithResource (acquireResourceFunc,func)
    local res = acquireResourceFunc()
    local ok, err = pcall(func,file)
    if resource then resource:close() end
    if not ok then error(err) end
  end

  function callWithFile (filename,mode,func) 
    return callWithResource( function () return io.open(filename,mode) end, func )
  end