lua-users home
lua-l archive

Re: Proposal: Add "level" argument to assert()

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


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

AltStyle によって変換されたページ (->オリジナル) /