lua-users home
lua-l archive

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


Jakub Piotr Cłapa <jpc-ml@zenburn.net> wrote:
>
> This could be quite easily achieved by borrowing the 'defer' mechanism from Go
> [1]. AFAIK this can be implemented quite cheaply in general but I do not know
> if it applies to the Lua (and LuaJIT) case.
>
> [1]: http://blog.golang.org/2010/08/defer-panic-and-recover.html

Lua would have to wrap any function that uses defer in a pcall, e.g.

function (a,b,c)
	-- do stuff
	defer function ()
		-- do stuff later
	end
	-- more stuff
end

-- becomes

function (...)
	return gosafe.call(function (a,b,c)
		-- do stuff
		gosafe.defer(function ()
			-- do stuff later
		end)
		-- more stuff
	end, ...)
end

-- and the gosafe package is something like

local stack = {}

function gosafe.defer(f)
	local t = stack[#stack]
	t[#t+1] = f
end

function gosafe.recover()
	local t = stack[#stack]
	t.recovered = true
	return t.error
end

local function unwind(ok, ...)
	local t = stack[#stack]
	stack[#stack] = nil
	if not ok then
		t.error = ...
	end
	for i = #t,1,-1 do
		t[i]()
	end
	if ok then
		return ...
	end
	if not t.recovered then
		error(t.error)
	end
end

function gosafe.call(f, ...)
	stack[#stack+1] = {}
	return unwind(pcall(f, ...))
end

Tony.
-- 
f.anthony.n.finch  <dot@dotat.at>  http://dotat.at/
FitzRoy, Sole: Southerly or southwesterly 6 to gale 8, occasionally severe
gale 9 at first in Sole, decreasing 5 at times except in east Sole. Rough or
very rough, occasionally high at first in Sole. Rain or showers. Moderate or
good, occasionally poor.