[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: RE: level argument for assert
- From: Thijs Schreijer <thijs@...>
- Date: Wed, 2 Jan 2013 11:05:03 +0000
> Due to the behaviour of argument lists, it doesn't make sense for a level
> argument:
> the error message would be dropped in any case; and the multi-return would
> fail.
Well, if you use it to return function values (more than 1), just leave the optional level argument out.
See this code example;
-- wrapper; extend assert with level argument
assert = function(test, msg, level, ...)
if test then return test, msg, level, ... end
error(msg, (level or 1) + 1) -- +1 is for this wrapper
end
-- Daurnimator code
function foo(some_cond)
assert(type(some_cond) == "boolean", "Must call foo() with a boolean", 2)
local data1, data2, data3 = "data1", "data2", "data3"
if some_cond then
return data1, data2, data3
else
return nil , "an error message"
end
end
print("Testing assert()\n")
print("Succesfull call:", pcall(assert, foo(true)))
print("Erroneous call :", pcall(assert, foo(false)))
print("Caveat :", pcall(assert, foo(false), 2)) -- foo return list is reduced, errmsg is lost!
print("Argument error :", foo("string"))
It will output;
Testing assert()
Succesfull call: true data1 data2 data3
Erroneous call : false an error message
Caveat : false 2
lua: asserttest.lua:22: Must call foo() with a boolean
stack traceback:
[C]: in function 'error'
asserttest.lua:3: in function 'assert'
asserttest.lua:9: in function 'foo'
asserttest.lua:22: in main chunk
[C]: ?
So to me it works perfectly well, the one caveat being that if you use it to check on returned function values, you cannot use the level argument with functions that return more than 1 value.
The upside is that it becomes very easy to use the other very common use of assert; argument checking (the way I added it to foo() in the example) with a proper level reported to the enduser.
Thijs