Skip to content

Instantly share code, notes, and snippets.

@Vurv78
Created August 14, 2021 21:16
Show Gist options
  • Save Vurv78/eeacd998a91697f2894dcea6516505c8 to your computer and use it in GitHub Desktop.
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.
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