lua-users home
lua-l archive

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


On Sat, Apr 9, 2011 at 7:48 PM, HyperHacker <hyperhacker@gmail.com> wrote:
> On Sat, Apr 9, 2011 at 11:31, Luiz Henrique de Figueiredo
> <lhf@tecgraf.puc-rio.br> wrote:
>>> it reports the error as being caused by the call to assert() itself,
>>> when the actual problem is at the point loadFile() was called with an
>>> invalid path.
>>
>> I don't see this as a problem. Having the traceback show assert is
>> a good thing in this case because it shows that an assertion failed.
>>
>>
>
> True, but it can also give the impression that the problem is a bug in
> your module. Especially if that module contains several internal
> functions, calling eachother in various ways, it may be a few calls
> deep that you finally need to check some argument (which may have come
> from a table, callback, vararg etc so checking it at the very
> beginning wouldn't be feasible) and find it's invalid. So your stack
> trace shows several of the internal functions of your module, making
> it not immediately obvious that the actual error is outside it.
>
> Anyway my main reasoning here is just "if error() has this, why
> doesn't assert()?" since assert() is essentially little more than a
> shortcut for "if not ... then error(...) end".

Well, one thing is that it is a common idiom to use assert() around a
function call that could return two values, nil and an error message,
on failure.

For example:

  myfile = assert(io.open('myfile.txt', 'r'))

...if io.open() fails, it will not throw an error itself but instead
return nil and an error message, which are then neatly turned into a
full error by assert().

But if you want to add an optional level parameter to this, you are
out of luck, because of course if you add another parameter:

  myfile = assert(io.open('myfile.txt', 'r'), 3)

...then it will replace the *second* parameter, setting "3" as the new
error message, rather than appending a third parameter.

You can avoid this by capturing the return values in local variables
first, of course, but it does feel like it makes the "rules of
assert() you should remember in order to use it" a little less clean
and simple.

-Duncan