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
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")
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.
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:
error throws an exception, so it exits the function without requiring return after it.
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.