Log In  

I know pcall isn't part of pico 8, which means you can't do regular Lua exception handling. I noticed though that coroutines swallow errors, and can return the error message. So I leveraged that to create a C#/Java style try catch finally function.

function try(t,c,f)
    local co=cocreate(t)
    local s,m=true
    while s and costatus(co)!="dead" do
        s,m=coresume(co)
        if not s then
            c(m)
        end
    end
    if f then
        f()
    end
end

cls()

try(function()
    print("hi ")
    --print("hi " .. nil)
end,
function(e)
    print("an error occurred:\n"..e)
end,
function()
    print("finally")
end)

To use just use it like above. The finally function is optional, so most people will probably use it like this:

try(function()
    -- code
end,
function(e)
    -- exception handler
end)

Enjoy, and if you like it feel free to kick a buck to my Patreon.

P#61361 2019-01-30 20:24

This is exactly what I am looking for, Thanks! I still can't seem to understand how it works...

P#61370 2019-01-30 22:15
:: Eniko
1

Are you confused about how to use it, or what trick it uses?

The trick it uses is that when an error happens in a coroutine, the coroutine silently fails and the second return value from 'coresume' contains the error message. So all this function does is run the code you give it as a coroutine, and keeps running it (because coroutines automatically yield sometimes in pico 8), and checks to see if an error happens.

When an error does happen, the second function gets called with the message. And regardless of whether or not an error happens the third function is called, if you pass it on.

P#61372 2019-01-30 23:03

[Please log in to post a comment]

About | Contact | Updates | Terms of Use
Follow Lexaloffle:        
Generated 2019-08-18 12:03 | 0.032s | 2097k | Q:16