lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


On Tue, Nov 23, 2010 at 09:03, Lorenzo Donati
<lorenzodonatibz@interfree.it> wrote:
>
> if not scheme:validate(record)
>  then error(...) end

Wouldn't this fit your bill?

function scheme_mt.__index:validate(tbl)
   local valid, err = true

   for k,v in pairs(tbl) do
      if self[k] then
         if type(v) ~= self[k].type then
            valid = false
            err = "Wrong type. Got "..type(v)..". "..self[k].type
.."was expected."
            break
         end

         valid,err = self[k].validator(v,tbl)
         if not valid then break end

      else
         valid = false; err = "Invalid field";
      end
   end

   for k,v in pairs(self)
      if v.mandatory = true and not tbl[k] then
         valid = false
         err = "Mandatory field missing"
         break
      end
   end

   return valid,err
end

function NewScheme(tbl)
   return setmetatable(tbl,scheme_mt)
end

assert(scheme:validate(my_table)

-- Pierre-Yves