Replacement for "assert"? (or "return end")

Simple, but not to me

Look at this code segment below, it’s just to much

local Character=Sender.Character
if not(Character and Character:IsA("Model"))then return;end

This one down here looks much better, but I don’t like errors printing when I simply just want to safety check

local Character=Sender.Character
assert(Character and Character:IsA("Model"),"Character is nil, or Character is not a Model instance.")

Is there some kind of middle ground?
like it functions like “return end” with an optional print or warn, but looks more like “assert”

might be stupid but I was wondering.

You can use a simple or statement

local Character = Sender.Character or warn("No character")

--// Logic goes here

Bear in mind this does not stop execution by itself! Hope this helps.

1 Like

(you could use error() instead of warn if you want execution to stop)

2 Likes
local Character = Sender.Character
if not Character then
    return warn("Character is nil")
end

logically speaking Player Character can either be a model or nil, idk why u check if its a model

1 Like

slight misunderstanding because of --! strict nonsense earlier.

This simplifies to:

if not character or not character:IsA("Model") then return end

The ; isn’t needed and wont change the behaviour of the code. What it does is that it makes sure that if the character doesn’t exist, or isn’t a model, it doesn’t run the code below it. If you inverse it it becomes:

if character and character:IsA("Model") then
	--code here
end

which translates to if the character exists and is a model, then run the following code.

assert is one way of triggering errors, but you can also trigger them using the built-in error function:

if not character or not character:IsA("Model") then
	error("Character doesn't or exist or isn't a model!")
end

Now when you want to either ignore errors, trigger them, convert them to warnings, handle them with special behaviour(such as retrying an API call), or even make the return an error code/message depends on your specific use case. You need to assess every situation that has this type of behaviour in it and figure out what’s more logical to do in case a specific error occurs.

For example when doing HTTP requests there’re errors that start with 5xx status codes, this means that the backend server made an error, which is likely to happen once in a while. In a situation like that it is worth to simply retry a request. However there’re also the 4xx status codes, that usually mean you did something wrong, or that the error will be persistent (meaning that it will happen again if you retry the request without changing something). In a situation like that it’s more worth to assess what the error is telling you and create special behaviour. For example the error code 429 often tells you to wait a while before redoing the request.

1 Like