assert

Asserts that condition is not nil and not false

Prototype

v = assert (v, message)

Description

Raises an error if value of v is nil or false.

Message is optional, defaults to "assertion failed!".

If no error, returns the value v.

assert (5 == 6, "oh no!") --> error: oh no!
It is very useful that assert returns the value on success, as you can build an assert into the same line that does something that might fail. For example:

assert (loadstring ("print 'hello, world'")) ()
In this case if the loadstring function succeeds it returns a function, that is then executed by the final brackets, otherwise you get an error message.

Lua functions

Topics