Assert - Just to be sure


assert(v, [, message]) Issues an error when the value of its argument v is false (i.e., nil or false); otherwise, returns all its arguments. message is an error message; when absent, it defaults to "assertion failed!"

Let's look at a few examples

We'll just try a few things out and see how they'll run. Remember to click on the green button to see what acctually happens with the code.


Something True

Let's try the obvious, just call assert with true.


As you can see, nothing happens and the function just returns true.

Something False

Annnnnd, let's see what happens with false


Wee, our first intentional error. Lua is so exciting!


Send it a message

According to the specification, if we give assert a second argument, it will be set as the error message.

                    assert(false, "Woosh")

This is extremely useful when tracking down which assert is crashing your program.

For some values of true

But beyond just true and false, assert will pretend that any other non-nil types are also true. Let's check

                    assert(function() end)

For other values of false

With the exception of false, only one other value, nil, evaluates to false.


Return value

When assert succeeds, what does it return? Let's explore

                    print(assert(true, "message"))
                    print(assert(1, 2, 3))

Found in the wild

To top it off, let's look at some real world uses of assert.

Testing your functions

Suppose that during the design of your program, you need to make sure that your program is correct. One way of doing this is to assert that the function will return some predefined values.

Take for example the problem of showing that \sum_{i=1}^n = \frac{n^2+n}{2}. We can sprinkle in a few asserts to make sure that our code is at least "visibly" correct.

What we type in:

                    function sum(n)
                        return (n*n - n)/2;
                    local s = 0
                    for i=1,100 do
                        s = s + i
                        assert(sum(i) == s, "Case "..i.." failed: expected "..s.." but got "..sum(i).." instead.")

Oops, looks like case 1 failed. Taking a closer look at the code, it becomes obvious where the problem is. (Can you spot the error? Hint: look at the math formula)

Guarding against nil values

One of the other common "idioms" of Lua is to use assert to "guard" against nil values. More specifically, suppose we want to read from a file that doesn't exist and we want to crash the program sooner rather than after wasting more resource. One way of doing this is via

What we type in:

                    local file = assert("fake_file.lua", "rb"))

If you're diligent, you may have also noticed that the error message states [string "stdin"]:1: fake_file.lua: No such file or directory rather than the more generic "assertion failed!" message. Don't worry, running the following code will hopefully alleviate your worries.

What we type in:

                    print("fake_file.lua", "rb"))

Whereas the convention in other languages is to throw an exception, for Lua, you just return nil and optionally throw in an error message.

blog comments powered by Disqus

The.Lua.Tutorialby Lee Gao.