lua-users home
lua-l archive

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


On Sep 24, 2014, at 9:22 AM, Tom N Harris <telliamed@whoopdedo.org> wrote:

> On Tuesday, September 23, 2014 01:09:36 PM Daurnimator wrote:
>> This seems to be asking for some form of selective 'catch'.
>> (as in, try{} catch(Exceptions.NOMEM) {}
> 
> Not sure I like the attempt to sneak static typing into a dynamic language. 
> 
> I tried thinking of some way to reduce the boilerplate needed to handle erros 
> but what I thought of basically boiled down to
> 
>   local this,errmsg = dosomething()
>   if not this then
>     -- handle error with errmsg
>   end
> 

What about pairing an error handler and a function using a closure factory?

-- Wrap a function f with a paired error handler eh
function errorwrap(f, eh)
	return function(...)
		local t = table.pack(f(...))
		if t[1] then return table.unpack(t) else return eh(f, t) end
	end
end

-- A function to wrap
function myfunc(x)
	if x < 0 then return nil, "must be positive" else return x end
end


-- An error handler: f=function, r=return values
function eh1(f, r)
	print("error in " .. tostring(f) .. ": " .. r[2])
end

local mywrappedfunc = errorwrap(myfunc, eh1)

mywrappedfunc(5)
mywrappedfunc(-5)

Can also be used to wrap pcall() to catch functions that throw errors.

—Tim