lua-users home
lua-l archive

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


> I think what you're looking for is not called assert().

Amen. The suggested usage does not fit the purpose.

I've never been able to understand why "assert" is used
when it's a question of user error.  A working program
should trap user errors with more informative messages than
"assertion failed".  Messages should be invoked by "error".
For which "level" is supported.

The Lua way is to give a message like e.g

   stdin:1: bad argument #1 to 'match' (string expected, got table)

"assert" should be used only in situations where the condition
is expected to be always true.  It should never bother you that
there is no "level" because the error message should never
appear. It's like "System error: program aborted!" from the early
days.  Or like the message "Somewhere something went horribly
wrong" that a colleague of mine used to put in his Fortran programs.

The way I was taught to use  "assert"  is exemplified int he C
code for the GMP package.  You don't use it directly but via
a macro.

    ASSERT(x>=0,"x should not be negative");

You define the macro to call the C "assert" macro while debugging
the program.  There are well over 3000 instances of ASSERT in
the code.  Once the program works, you don't take out all the
asserts but redefine the macro to  generate no code at all.  GMP
automates all that by a preprocessor variable WANT_ASSERT.

The Lua analogue is (inside your package)

   local assert = assert
    ...
   assert(x>=0,"x should not be negative")

and once the program works,

   local assert = function() end

In production, users will sooner or later uncover a mistake.
That's when you restore the original assert, debug it, and
deactivate it again.