Garry's Mod Wiki

assert

  any, any, vararg assert( any expression, string errorMessage = "assertion failed!", ... )

Description

If the result of the first argument is false or nil, an error is thrown with the second argument as the message.

Arguments

1 any expression
The expression to assert.
2 string errorMessage = "assertion failed!"
The error message to throw when assertion fails. This is only type-checked if the assertion fails.
3 vararg returns = nil
Any arguments past the error message will be returned by a successful assert.

Returns

1 any
If successful, returns the first argument.
2 any
If successful, returns the error message. This will be nil if the second argument wasn't specified.

Since the second argument is only type-checked if the assertion fails, this doesn't have to be a string.

3 vararg
Returns any arguments past the error message.

Example

The assertion is successful, and the result of the first argument is returned.

local ABC = assert(print) print(ABC)
Output: function: builtin#25

Example

Since the first argument evaluates to false, an error is thrown.

assert(print == 1, "print is not equal to 1!")
Output: [ERROR] lua_run:1: print is not equal to 1!

Example

Examples of return behaviour.

print(assert(5)) print(assert(true, "foo", 2, {}))
Output:
5 true foo 2 table: 0x36409278