lua-users home
lua-l archive

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


meta lua sounds like a simple way to edit the standard assert function so it performs as you want without having to change or complicate things ?


On Sat, Apr 9, 2011 at 11:34 AM, Enrico Colombini <erix@erix.it> wrote:
On 09/04/2011 16.41, HyperHacker wrote:
assert() is a convenient function for checking for error conditions in
one statement. A common _expression_:
if not foo then error("Invalid foo") end
can be shortened to:
assert(foo, "Invalid foo")

I like assert, but I rarely use it in Lua because of performance consideration when I need more information. Maybe I'm mistaken (I would gladly be) but I'm under the impression that:

 local f = assert(io.open(fname, 'r'), 'cannot open: ' .. fname)

always performs the string concatenation, regardless of success or failure, while the if..then equivalent:

 local f = io.open(fname, 'r')
 if not f then print('cannot open: ' .. fname) end

only concatenates in case of error. In some cases (e.g. function argument check) this could lead to a significant difference in execution time and memory usage.

Maybe a varargs (print-like) version of assert() could avoid this dilemma. Or a generic:

 assert(cond, func, ...)

that calls func(...) in case of assertion failure, before exiting.

--
 Enrico