Quirrel4.41.0

assert

Global, available without an import
assert(condition, [message: function|string])

Throws an error when condition is false.

examples/globals/assert-basic.nut
let hitPoints = 100
assert(hitPoints > 0)   // condition holds: nothing happens

println("hitPoints =", hitPoints)
Output:
hitPoints = 100

Parameters

conditionanychecked with the same rules as if
messagefunction|stringtext for the error, or a function that returns it optional

Return value

null when condition is true.

Errors

Throws assertion failed when condition is false and no message is given. Otherwise throws message itself, or the string that a function message returns.

Notes

message is read lazily: when it is a function, the function runs only after condition has already failed, and only then. A condition that holds never calls it, so building the message can be as expensive as it needs to be.

Example

examples/globals/assert.nut
try { assert(1 + 1 == 3, "math is broken") } catch (e) { println("assert(1+1==3, ...) throws:", e) }

// the message may be a function; it runs only when the assertion actually fails
local pings = 0
function build_message() { pings += 1; return "built on demand" }

assert(true, build_message)
println("pings =", pings)                              // still 0: condition held, message unused

try { assert(false, build_message) } catch (e) { println("assert(false, ...) throws:", e) }
println("pings =", pings)                               // now 1: message was built to form the error
Output:
assert(1+1==3, ...) throws: math is broken
pings = 0
assert(false, ...) throws: built on demand
pings = 1

See also

errorWrites its arguments to the error stream.
globalsmodule index