Last active
October 27, 2019 08:08
-
-
Save h-michael/7a70dd6c037035f068c63622062db734 to your computer and use it in GitHub Desktop.
simple function arguments type check function
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 type_check(...) | |
local function type_name(t) | |
assert(type(t) == 'string') | |
if t == 't' or t == 'table' then return 'table' end | |
if t == 's' or t == 'string' then return 'string' end | |
if t == 'n' or t == 'number' then return 'number' end | |
if t == 'b' or t == 'boolean' then return 'boolean' end | |
if t == 'f' or t == 'function' then return 'f' end | |
if t == 'nil' then return 'nil' end | |
if t == 'th' or t == 'table' then return 'thread' end | |
if t == 'u' or t == 'userdata' then return 'userdata' end | |
error(string.format("invalid type name '%s'", t)) | |
end | |
local t = {...} | |
for _, v in pairs(t) do | |
assert(type(v) == 'table', 'Expected table, got %s', type(v)) | |
local arg_type = type(v[1]) | |
local _type, is_optional = v[2]:gsub('^!', '') | |
if is_optional == 1 then | |
is_optional = true | |
else | |
is_optional = false | |
end | |
local expected_type = type_name(_type) | |
if is_optional then | |
assert((arg_type == expected_type) or arg_type == 'nil', string.format("Expected %s or nil, got %s", expected_type, type(v[1]))) | |
else | |
assert(arg_type == expected_type, string.format("Expected %s, got %s", expected_type, type(v[1]))) | |
end | |
end | |
end | |
function test(a, b, c) | |
type_check({a, 'n'}, {b, 's'}, {c, '!t'}) | |
end | |
print('===case1===') | |
test(1, 'a', {1}) | |
print('===case2===') | |
test(1, 'a', nil) | |
print('===case3===') | |
test(1, 2, 3) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment