lua-users home
lua-l archive

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


As a specific example of doing this without closures or pack, here is a routine (from memory and without the aid of caffeine) for closing a file promptly when done even in the event of an error.

	local function finish( file, success, ... )
		file:close()
		if success then
			return ...
		else
error( ( ... ) ) -- Probably should adjust the stack level for the message
		end
	end

	function doWithOpenFile( fn, fp )
		local file = assert( io.open( fp ) )
		return finish( file, pcall( fn, file ) )
	end

I've used this enough that I wrapped the final step of the finish routine into a pcall2call function that does the appropriate level adjustment for the error return as well. You can find more examples in the archive if you search on pcall2call.

I don't have a proposed syntax, but it feels like there ought to be a more natural way to deal with this and with other cases where one needs to process the results of a function returning an unknown number of arguments. The specific case here could b addressed with a variety of exception handling mechanisms, but if one wants to actually process the return arguments then one is stuck. For example, consider:

	local reportErrors( success, fp, msg )
		if success then
			return
		end
		print( "error:", fp, msg )
		error( msg )
	end

	local function finish( file, fp, success, ... )
		file:close()
		reportErrors( success, fp, ... )
		print( fp, ... )
		return ...
	end

	function openExtractPrintAndClose( extractor, fp )
		local file, msg = io.open( fp )
		reportErrors(  file, fp, msg )
		return finish( file, fp, pcall( extractor, file ) )
	end

Mark