enum.lua (1111B)
1 local error, type = error, type 2 3 local module = {} 4 local function to_int(enum, val) 5 local t = type(val) 6 if t == "string" then 7 return enum[val] or error("Invalid enum value "..val, 2) 8 elseif t == "number" or t == "cdata" then 9 return val 10 else 11 error("Invalid enum type "..t, 2) 12 end 13 end 14 module.to_int = to_int 15 16 local function to_str(enum, val) 17 local t = type(val) 18 if t == "string" then 19 return val 20 elseif t == "number" then 21 return enum[val] or val 22 else 23 error("Invalid enum type "..t, 2) 24 end 25 end 26 module.to_str = to_str 27 28 function module.make_enum(tab) 29 -- do not modify list while iterating 30 local new = {} 31 for _,p in ipairs(tab) do 32 assert(#p == 2) 33 local str, i = p[1], p[2] 34 assert(not new[str]) 35 new[str] = i 36 if not new[i] then new[i] = str end 37 end 38 return new 39 end 40 41 function module.filter_min_max(enum, min, max) 42 local new = {} 43 for k,v in pairs(enum) do 44 if type(k) == "number" then 45 if k >= min and k <= max then new[k] = v end 46 else 47 if v >= min and v <= max then new[k] = v end 48 end 49 end 50 return new 51 end 52 53 return module