Any ways of improving this repetitive code?

So I’ve been making a type checker for my RemoteEvents and one of my RemoveEvents has 7 variables and my code ended up looking like this:

if typeof(itemID) ~= "string" or typeof(slotNum) ~= "number" or typeof(itemAmt) ~= "number" or typeof(itemName) ~= "string" or typeof(itemRarity) ~= "number" or typeof(itemPhoto) ~= "Instance" then
	error(player.DisplayName .. " Wrong type of data sent. Exiting function.")
return end
if itemModel ~= nil then
	if typeof(itemModel) ~= "Instance" then
		error(player.DisplayName .. " Wrong type of data sent. Exiting function.")
	return end
end

Is there a better approach to this?

You could split up each variable into 7 different assert functions (documentation). It will make your code longer but more readable.

assert(typeof(dad) == "Instance", "Variable 'dad' must be an Instance")
assert(typeof(mom) == "Instance", "Variable 'mom' must be an Instance")
assert(typeof(siblings) == "table", "Variable 'siblings' must be a table")

There’s also typed Luau (still in beta)

1 Like

I also wanted to use assert continuously however due to this post, I wasn’t so sure.

1 Like

Interesting. I never really thought about it.

Anyways, are you sure you need this code at all? You could just make sure to never set the variables to anything other than their intended type, and it would have no issue whatsoever.

1 Like

assert and type/typeof are very fast in the new Lua VM so as long as you aren’t doing a bunch of string concatenation it should be fine; constants like strings don’t really have an overhead, and the function calls aren’t very expensive.

With regard to the code in the OP, even without using assert you can reduce the code some by taking advantage of a few things:

  1. error throws an exception, so it exits the function without requiring return after it.
  2. typeof(nil) doesn’t error

The second point in particular is helpful since you don’t have to check if ItemModel is nil; you can just check that it’s either an Instance or nil, which makes the code less verbose IMO.

For something as in-depth as this with a bunch of different type checks going on I would recommend using an existing library for it though.

t by @osyris is a library made specifically for this stuff and it will probably save you a lot of headache later on.

2 Likes

I only do these to my RemoteEvents (Client to Server) to avoid abuse.

Oh I never knew about this. I thought it was just some color for devs to easily read their logs.

Oh I never knew this existed. I’ll definitely look into this later.

I recommend throwing asserts in whenever you think programmer error could occur. The real value is finding errors you might have logically missed.

1 Like

How do I go about this? Do I throw asserts whenever I call for a value/function and the like?