I’m one of those fans of
assert: it makes things shorter, simpler, cleaner. But its performance issues make custom made asserts be better than the built-in one. That’s affirm, the good assert.
If you haven’t yet, check out this post.
They’re a little bit longer than affirm statements and not that readable if you ask me. Done.
if not typeof(value) == "number" then error(string.format("expected number, got %s", typeof(value)), 2) end
affirm(typeof(value) == "number", "expected number, got %s", typeof(value))
affirm is really similar to
assert, only adding a third argument:
affirm(condition: any, errorMessage: any?, ...: string | number?): ()
Arguments after the error message will automatically format to the second argument, no need to call
string.format. See the example:
local affirm = require(path.to.this.module) local var1 = 687 local var2 = "foo" affirm(var1 > 0, "number isn't positive [%+i]", var1) -- OK affirm(typeof(var1) == "number", "expected number, got %s", typeof(var1)) -- OK affirm( typeof(var2) == "number", "expected number, got %s", typeof(var2) ) -- Error: expected number, got string
The second argument,
errorMessage, accepts any valid data type as value. This includes tables or instances to be thrown as errors.
The error message points to the caller of the failed function rather than the function that calls
error(..., 3)internally. Useful for debugging.
Trying to format an error message with invalid arguments (anything other than strings or numbers) will throw a nice and detailed error pointing these bad arguments.
affirm(false, "%s, %s", "Nice", Instance.new("Part")) -- "Nice" is #1, Part is #2
affirm() -> following arguments expected strings or numbers, got: #2 Instance
The function is completely typed and documented, open-source under the MIT License (do whatever you want with the code) and available as a wally package. Enjoy !
Also, if you ask me for the name:
affirm has the same number of characters as
assert and means the same.