Problems with Understanding Assert

You can write your topic however you want, but you need to answer these questions:

  1. What do you want to achieve? I want to understand how to use assert

  2. What is the issue? I don’t understand what it means on the wiki

Could someone give me an example of how assert is used?

Thanks for reading!

4 Likes

It’s a function you can use to manually throw errors in your code. If the given condition is false, it will error with a custom message.

assert(true, "Error message")
--> No errors will be thrown

assert(false, "Error message")
--> An error will be thrown with the text "Error message"

Here’s an example of how this might be useful:

local function doSomethingWithANumber(number)
   assert(type(number) == "number", "Argument 1 must be a number")
end

Which does the same thing as:

local function doSomethingWithANumber(number)
   if type(number) ~= "number" then
      error("Argument 1 must be a number")
   end
end

This is helpful when you want to validate/test your code, as issues you have can be found and fixed (as they are errors, they are super obvious when they occur).

49 Likes

to add on, assert returns both of its arguments,

so you could do

if assert(cond, custom_msg) then

end

if everything went ok and no exception was thrown.

3 Likes