smr/src/lua/types.lua

52 lines
1000 B
Lua

--[[
Type checking, vaguely inspired by Python3's typing module.
]]
local types = {}
function types.positive(arg)
local is_number, err = types.number(arg)
if not is_number then
return false, err
end
if arg < 0 then
return false, string.format("was not positive")
end
return true
end
--Basic lua types
local builtin_types = {
"nil","boolean","number","string","table","function","coroutine","userdata"
}
for _,type_ in pairs(builtin_types) do
types[type_] = function(arg)
local argtype = type(arg)
if argtype ~= type_ then
return false, string.format("was not a %s, was a %s",type_,argtype)
end
end
end
function types.matches_pattern(pattern)
return function(arg)
local is_string, err = types.string(arg)
if not is_string then
return false, err
end
if not string.match(arg, pattern) then
return false, string.format(
"Expected %q to match pattern %q, but it did not.",
arg,
pattern
)
end
end
end
function types.check(...)
end
return types