Skip to main content

Assert

You'll see assert calls dotted around, often doing things such as:

local screen = assert(GetPart("Screen"), "no screen connected")

This may be confusing to people who have never seen assert before, but all it is doing, is taking the first parameter, checking if it is false or nil, and if it is, throwing the text in the second parameter as an error, but if it isn't, it returns the first parameter.

For example, doing something like:

local value = assert(32, "value is nil!") -- this will run fine
print(value) -- '32'
local value = assert(nil, "value is nil!") -- 'value is nil!'
print(value) -- this will not run

This same logic applies to the return value of GetPart(s)(FromPort), allowing us to easily throw useful errors if no object is connected, which helps prevents the whole class of "attempt to index nil with ..." relating to objects being disconnected.

Another benefit of this is for people who use full typechecking (most easily accessible in Visual Studio Code, using the typechecking part of this wiki), it removes the warnings about the possibility of the object being nil whenever you reference members of it.