lua-users home
lua-l archive

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

On 22 November 2011 16:40, HyperHacker <> wrote:
> Funny, I had a very similar idea the other day:
> #!/usr/bin/env lua
> local errhandler = coroutine.create(function(what)
>        while true do
>                io.stderr:write("Error: " .. what .. '\n')
>                what = coroutine.yield(what ~= "It's broken")
>        end
> end)
> function throw(what)
>        local ok, stat = coroutine.resume(errhandler, what)
>        if not ok then error("Error in error handler: " .. tostring(stat)) end
>        if not stat then error("Unrecoverable error: " .. tostring(what), 2) end
> end
> pcall(function()
>        print("one")
>        throw("I goofed")
>        print("two")
>        throw("It's broken")
>        print("this should never be reached")
> end)
> print("three")
> throw("It's broken")
> print("this should also never be reached")

Interesting, but strange IMO; the error handler doesn't really need to
be a loop: it could just be a function that returns; and the caller
does the yielding. (we also have an inversion of control)
Otherwise, I spose I have a similar thing through recursion in my script.
Also, the ability to provide values when resuming a thread was
important for me:
    arg = assert( arg , "Missing argument" )
The error is fatal; but it can be fixed with extra input from caller/user.

> If it were possible to kill coroutines, the error handler could even
> do that for severe errors. (In your own applications, you could just
> have a table of coroutines that run one after another, and just remove
> it from there...)

In my script that is achieved by not recursing.

Additionally as a note: coroutines are garbage collected; so no clean
up is really needed :)

> Related: I'd love a standardized warning system in Lua. It could be as
> simple as:
> function warn(...)
>    local here = debug.getinfo(2, 'Sl')
>    print(("Warning: %s:%d:"):format(here.short_src, here.currentline), ...)
> end
> and then you just replace it with your own function if you want to
> handle warnings differently.

This is more related to my other thread:
==> just raise an error object with a tostring metamethod: tostring =
function(o) return "Warning: " .. o.msg end
Gladly this seems to be fixed in lua 5.2; so there's no problems with
it now (just gotta get it fixed in luajit)

> --
> Sent from my toaster.