You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
54 lines
1.1 KiB
Lua
54 lines
1.1 KiB
Lua
local error, type = error, type
|
|
|
|
local module = {}
|
|
local function to_int(enum, val)
|
|
local t = type(val)
|
|
if t == "string" then
|
|
return enum[val] or error("Invalid enum value "..val, 2)
|
|
elseif t == "number" or t == "cdata" then
|
|
return val
|
|
else
|
|
error("Invalid enum type "..t, 2)
|
|
end
|
|
end
|
|
module.to_int = to_int
|
|
|
|
local function to_str(enum, val)
|
|
local t = type(val)
|
|
if t == "string" then
|
|
return val
|
|
elseif t == "number" then
|
|
return enum[val] or val
|
|
else
|
|
error("Invalid enum type "..t, 2)
|
|
end
|
|
end
|
|
module.to_str = to_str
|
|
|
|
function module.make_enum(tab)
|
|
-- do not modify list while iterating
|
|
local new = {}
|
|
for _,p in ipairs(tab) do
|
|
assert(#p == 2)
|
|
local str, i = p[1], p[2]
|
|
assert(not new[str])
|
|
new[str] = i
|
|
if not new[i] then new[i] = str end
|
|
end
|
|
return new
|
|
end
|
|
|
|
function module.filter_min_max(enum, min, max)
|
|
local new = {}
|
|
for k,v in pairs(enum) do
|
|
if type(k) == "number" then
|
|
if k >= min and k <= max then new[k] = v end
|
|
else
|
|
if v >= min and v <= max then new[k] = v end
|
|
end
|
|
end
|
|
return new
|
|
end
|
|
|
|
return module
|