Assert

From Pico-8 Wiki
Jump to navigation Jump to search
assert( cond, [message] )
Causes a runtime error if a conditional expression is false.
cond
The conditional expression to assert.

message
A message to print when the assertion fails.

return-value
All arguments as passed to assert() in a tuple (if the assert didn't fail).

The purpose of assert() is to confirm what is assumed to be true any any given point. If the conditional expression evaluates to false, assert() triggers a runtime error, and PICO-8 stops the program and reports the error and line number of the assert.

An optional message may be passed to assert() to replace the default message, "assertion failed".

Caution: A runtime error inside of a coroutine will abort the coroutine, but will not automatically stop the application and report the error. Assertions inside of coroutines must be detected by the code that spawns and monitors the coroutines. See coresume() for information on detection and reporting.

Examples

function divide(num, denom)
  assert(denom != 0, 'cannot divide by zero')
  return num/denom
end

print(divide(12, 4))  -- 3
print(divide(7, 0))   -- runtime error, assertion failed

See also