lua-users home
lua-l archive

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


On 18 September 2010 11:32, Javier Guerra Giraldez <javier@guerrag.com> wrote:
> i agree that try/catch syntax is easier to use than pcall(); but i've
> rarely needed it.  this is my current approach to fake it for those
> rare occasions:
>
>
> ---------- try.lua ----------------------
> local function returner (c, r, ...)
>        if r then return ... end
>        return c(...)
> end
>
> return function (t, c)
>        return returner (c, pcall(t))
> end
> ----------------------------------------
>
> usage sample:
>
> ---------- test_try.lua ----------
> local try = require "try"
>
> try (function ()
>        print 'one'
>        assert (true, 'not fail')
>        print 'two'
>        assert (false, 'do fail')
>        print 'three'
> end, function (e)
>        print ('catch:', e)
> end)
> --------------------------------------
>
> #> lua test.lua
> one
> two
> catch!   test.lua:7: do fail
>
> definitely not worth modifying Lua just to add the keywords.
>
> now, you bind the Lua core with your specific type system.... that's
> just too far in the specialization.  Rob's suggestion is much more
> generic
>
> --
> Javier
>
>

Looks like you just made xpcall:

xpcall( function()
    -- try code
    if getvar() then
    else
         error(setmetatable({"an","error","object"},{__type="err"}))
    end
end , function ( err )
    -- catch code, you can dispatch/swicth on err:
    if (getmetatable(err) or {}).__type == "err" then
        print(table.concat(err))
    else --propgate error
        error(err)
    end
end )