lua-users home
lua-l archive

Re: How to make sure some operations in ANY situation? (aka: with statement in Python)

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


local function finish( success, ... )
	if not success then
		pcall( cleanup ) -- First error wins, so pcall cleanup
		error( (...) ) -- May want to play with error level for better reporting
	else
		cleanup() -- Errors in cleanup would now be interesting
		return ...
	end
end
return finish( pcall( problem_function ) )
If you never care about errors in cleanup, then you can just always pcall it in the finish function.
Let's take this pattern and use it with files...
local function finish_with_file( f, success, ... )
	if not success then
		pcall( io.close, f )
		error( (...) )
	else
		io.close( f )
		return ...
	end
end
function with_file_do( path, fn )
	local f = assert( io.open( path ) )
	return finish_with_file( f, pcall( fn, f ) )
end
Mark

AltStyle によって変換されたページ (->オリジナル) /