lua-users home
lua-l archive

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


Try something more like the following:

	local scope = makeScope()

	scope:register( finalizer )

	local result = bar( scope )

	scope:close()

	return result

 Here scope plays the role of your U object. The need to invoke close on the scope after the call to bar keeps it alive.

If capturing result seems like a pain, then wrap the pattern in a standard method on scope:

	scope:executeAndClose( bar, scope )

Which could be defined as:

	local function pcall2call( success, ... )
		if not success then
			error( ( ... ) )	-- Note: Play with level offset for better messages
		else
			return ...
		end
	end

	local function _executeAndClose_finish( scope, ... )
		scope:close()
		return pcall2call( ... )
	end

	function Scope:executeAndClose( ... )
		return _executeAndClose_finish( self, pcall( ... ) )
	end

[ Side note: Per the other current LuaJIT thread, this is also an example of my usage of varargs in generic code. ]

Mark

P.S. Other interesting things to do include having the register function return a function that can be used to execute the finalizer early or cancel it or whatever though that results in more data creation and collection traffic.