Advertisement
Rochet2

ensure format

Mar 26th, 2016
298
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.31 KB | None | 0 0
  1. local valid_types = {
  2.     ["nil"] = true,
  3.     ["number"] = true,
  4.     ["string"] = true,
  5.     ["boolean"] = true,
  6.     ["table"] = true,
  7.     ["function"] = true,
  8.     ["thread"] = true,
  9.     ["userdata"] = true,
  10. }
  11. local function ensure_fmt(fmt, args)
  12.     for k, expected in pairs(fmt) do
  13.         local exp_type = type(expected)
  14.         if exp_type == "string" then
  15.             assert(valid_types[expected], "invalid type in fmt: "..tostring(expected))
  16.             local typ = type(args[k])
  17.             if typ ~= expected then
  18.                 return false, string.format("%s was of type %s, %s expected", tostring(k), typ, expected)
  19.             end
  20.         elseif exp_type == "table" then
  21.             local typ = type(args[k])
  22.             if typ ~= exp_type then
  23.                 return false, string.format("%s was of type %s, %s expected", tostring(k), typ, exp_type)
  24.             end
  25.             local succ, err = ensure_fmt(expected, args[k])
  26.             if not succ then
  27.                 return succ, err
  28.             end
  29.         else
  30.             error("unknown expecatation in fmt: "..tostring(expected))
  31.         end
  32.     end
  33.     return true
  34. end
  35.  
  36.  
  37. -- some example usage
  38. local fmt = {"number", "string", {}, {"number", "string", ke = {}}}
  39. local arg = {1, "asd", {}, {1,"str", ke = {}}}
  40. print(ensure_fmt(fmt, arg))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement