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!"
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.
Let's try the obvious, just call assert with true.
assert(true)
As you can see, nothing happens and the function just returns true.
Annnnnd, let's see what happens with false
assert(false)
Wee, our first intentional error. Lua is so exciting!
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.
But beyond just true and false, assert will pretend that any other non-nil types are also true. Let's check
assert(1) assert(0) assert("false") assert({false}) assert(function() end) assert(newproxy())
With the exception of false, only one other value, nil, evaluates to false.
assert(nil)
When assert succeeds, what does it return? Let's explore
print(assert(true, "message"))
print(assert(1, 2, 3))
To top it off, let's look at some real world uses of assert.
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.
function sum(n) return (n*n - n)/2; end 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.") end
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)
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
local file = assert(io.open("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.
print(io.open("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