Created
August 14, 2021 21:16
-
-
Save Vurv78/eeacd998a91697f2894dcea6516505c8 to your computer and use it in GitHub Desktop.
A lua function that checks that arguments of correct types. Supports vararg amount of types and mimics native lua errors exactly.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
local function error_fmt(level, msg, ...) | |
error( string.format(msg, ...), level + 1 ) | |
end | |
local function checkargtype(val, argnum, func_name, ...) | |
local expected_msg = {} | |
local t = type(val) | |
local count = select('#', ...) | |
for i = 1, count do | |
local expected = select(i, ...) or "nil" | |
if t == expected then | |
return | |
end | |
expected_msg[i] = expected | |
end | |
local expected_str = table.concat(expected_msg, " or ") | |
if t ~= expected then | |
error_fmt(2, "bad argument #%d to '%s' (%s expected%s)", argnum, func_name, expected_str, count == 1 and string.format(", got %s", t) or "") | |
end | |
end | |
function add_two(a, b) | |
checkargtype(a, 1, "add_two", "number") | |
checkargtype(b, 2, "add_two", nil, "number") | |
return a + (b or 6) | |
end | |
local function setmetatable(a, b) | |
checkargtype(a, 1, "setmetatable", "table") | |
checkargtype(b, 2, "setmetatable", nil, "table") | |
end | |
print( pcall(setmetatable, {}, nil) ) | |
print( pcall(setmetatable, {}, 2141124) ) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment