[added] assert methods return first argument so they can be used inline

This commit is contained in:
Max Cahill 2020-05-29 16:20:26 +10:00
parent 348653a6dd
commit 591ba1d7a9

View File

@ -3,6 +3,7 @@
- avoid garbage generation upon success,
- build nice formatted error messages
- post one level above the call site by default
- return their first argument so they can be used inline
default call is builtin global assert
@ -23,16 +24,18 @@ local function _extra(msg)
if not msg then
return ""
end
return "(note: " .. msg .. ")"
return "\n\n\t(note: " .. msg .. ")"
end
--assert a value is not nil
--return the value, so this can be chained
function assert:some(v, msg, stack_level)
if v == nil then
error(("assertion failed: value is nil %s"):format(
_extra(msg)
), 2 + (stack_level or 0))
end
return v
end
--assert two values are equal
@ -44,6 +47,7 @@ function assert:equal(a, b, msg, stack_level)
_extra(msg)
), 2 + (stack_level or 0))
end
return a
end
--assert two values are not equal
@ -53,6 +57,7 @@ function assert:not_equal(a, b, msg, stack_level)
_extra(msg)
), 2 + (stack_level or 0))
end
return a
end
--assert a value is of a certain type
@ -65,15 +70,19 @@ function assert:type(a, t, msg, stack_level)
_extra(msg)
), 2 + (stack_level or 0))
end
return a
end
--replace everything in assert with nop functions, for near-zero overhead on release
--replace everything in assert with nop functions that just return their second argument, for near-zero overhead on release
function assert:nop()
local nop = function(self, a)
return a
end
setmetatable(self, {
__call = function() end,
__call = nop,
})
for k, v in pairs(self) do
self[k] = function() end
self[k] = nop
end
end