lua-users home
lua-l archive

Re: validating Lua data

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


Hello all,
A very good routine validate. Here is another different version
I obtained by transforming print_r (from the wiki). As I have
several tables to verify I prefer not to call error, but to return
true or false, and print the errors in stdin. At the end of validation
if some returned errors are true I can abort the program.
Apart it is convenient to name the table in test with the aim to know where is the problem:
-- verifies if table t has at least the same fields as
-- indicated in table o and of same type
local function table_verify(o, t, name, done)
 local key, o1
 local err = false
 done = done or {}
 for key, o1 in pairs(o) do
 if type(o1) == "table" and not done[value] then
 done[o1] = true
 if t[key] == nil then
 print(name .. "." .. key .. ": does not exist or incorrect")
 err = true
 else
 err = err or table_verify(o1, t[key], name .. "." .. tostring(key), done)
 end
 else
 if t[key] == nil or type(o1) ~= type(t[key]) then
 print(name .. "." .. key .. ": does not exist or incorrect")
 err = true
 end
 end
 end
 return err
end
-- schema and data assignations ...
table_verify(schema, data, "data")
------------------------------------------
I recognize validate as more Lua than table_verify but both work well.
Manel.

AltStyle によって変換されたページ (->オリジナル) /