lua-users home
lua-l archive

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


On Tue, Apr 28, 2015 at 9:26 AM, Javier Guerra Giraldez
<javier@guerrag.com> wrote:
> On Tue, Apr 28, 2015 at 10:44 AM, Coda Highland <chighland@gmail.com> wrote:
>> Speaking of meta-programming: There's always the option to introduce
>> try/catch/end syntax in a preprocessor. :P
>
> it's also very doable with anonymous functions (untested, and might be
> better with xpcall):
>
> local function onrets(catch, ok, res1, ...)
>    if ok then
>       return res1, ...
>    else
>       return catch(res1)
>    end
> end
>
> function try(f,catch)
>    return onrets(catch, pcall(f()))
> end
>
>
> ----- use as:
>
> try(function()
>
>     -- this is the 'try' part
>
> end,function(err)
>
>     -- and on any error, this will be called
>
> end)
>
>
> if the 'try' part returns successfully, this will return all its
> values.  if it signals an error, the 'catch' part is called.  any
> returns from the catch part would be passed to the original caller, if
> it signals a new error, it would be propagated out of the whole
> expression.
>
> --
> Javier
>

Sure, something like that was my assumption as to what the syntax
would expand into after preprocessing, or perhaps inlined instead of
wrapped through another function to reduce the overhead a little bit.

/s/ Adam