Assert Behavior

I use assert() liberally as a sanity check in a large project. I noticed it never crashes the program, regardless of debug or release build. This makes it effectively no different than an early return with an error message, or a failed error() call, but happens unexpectedly and probably leaves the program in an unrecoverable state.

Is there a way to enable the expected crashing behavior? Otherwise, maybe creating a utility function would be a workaround.

-- something like this
function myassert(condition, message)
    -- assert success
    if condition then return true end
    -- print error message to stderr
    -- wrap in `pcall()` to avoid early return
    pcall(function() error(message) end)
    -- exit failure regardless of debug or release
    sys.exit(1)
end
1 Like

You can set a custom error handler:

function init(self)
	-- set this once globally on startup
	sys.set_error_handler(function(source, message, traceback)
		print(source, message, traceback)
		sys.exit(1)
	end)

	-- assert() and error() and any Lua error will end up in the error handler above
	assert(1 == 2)
end
3 Likes

Thank you, this is probably good enough.

More information for future readers:

2 Likes