From 591ba1d7a949950990cf7fa56098ffc670218e46 Mon Sep 17 00:00:00 2001 From: Max Cahill <1bardesign@gmail.com> Date: Fri, 29 May 2020 16:20:26 +1000 Subject: [PATCH] [added] assert methods return first argument so they can be used inline --- assert.lua | 19 ++++++++++++++----- 1 file changed, 14 insertions(+), 5 deletions(-) diff --git a/assert.lua b/assert.lua index 7dbb485..978ce10 100644 --- a/assert.lua +++ b/assert.lua @@ -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 @@ -16,23 +17,25 @@ local _assert = assert local assert = setmetatable({}, { __call = function(self, ...) return _assert(...) - end, + end, }) 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