Your phone or window isn't wide enough to display the code box. If it's a phone, try rotating it to landscape mode.
- Code: Select all
function mod.add_itemtype(id,name,groups,stackmax)
if type(id) == "string" and type(name) == "string" and type(groups) == "table" and type(stackmax) == "number" then
-- important stuff here
else
-- throw an error
error("add_itemtype() was called with incorrect parameters")
end
end
However, I soon realized that it is probably quite inefficient to check all of those parameters this way, and that there is probably a better way, either saving loading time or resulting in code which is much shorter in the type-checking part.
If there is no better way, I am considering removing type checking entirely. This would give less information in the error message about which function produced the error, and you would have to check the stack trace - the error message would be something cryptic like "Table expected, got nil" and not of much use, except when you have to determine which parameter got the wrong type, and that is after you find in the stack the function which produced the error. I would prefer that my mod's functions give some helpful debug information via the error message in the event that such an error occurs, instead of producing a cryptic message and requiring the user to examine the stack before looking at the code where they called the function. You could say that you should still use the stack to find which line of which script has the function call which caused the error, which is true - but some users may not be that "advanced", and would possibly find it somewhat more straightforward to go look at where they called that function mentioned in the error message, and find which parameter is an incorrect type.
So is there a better way to check the type of many parameters at once (iteratively, like ipairs)?
If there is not any better way (or even if there is a better way), would it be best to remove type checking entirely?