lua-users home
lua-l archive

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


2012/10/23 David Collier <myshkin@cix.co.uk>:
> My colleague has pointed out that for a simple situation where I am
> returning an error status and a single value, I can use nil in place of
> the value to indicate an error.
>
> But obviously that doesn't work for more return values.

It does work, you even have two possibilities. If each return value is
independent, you can return either a value or nil for each. If errors
are global, you either return a list of values, or nil followed by the
error message. That's a very common idiom. For example :

function foo()
    local a = getA()
    local b = getB()
    local ok = isOK()
    if ok then
        return a,b
    else
        return nil,getError()
    end
end

local a,b = assert(foo())

> I don't quite understand why the syntax of "if" can't be extended to say
> that if it is given a list of values it tests the first one. But maybe
> something else would graunch to a halt then.

It's already working like that. For example :

function foo()
    return false,42
end

if foo() then
    print("this message is not displayed")
else
    print("that message is displayed")
end