lua-users home
lua-l archive

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


Norman Ramsey <nr <at> eecs.harvard.edu> writes:

> Has anybody thought about the moral equivalent of
> XML DTD or XML Schema for describing valid Lua data?

The function below validates a table against a "schema" table.
It makes sure that all of the keys in your table and subtables appear
in the schema (although not vice-versa, to allow for optional keys),
and that the types are the same.

There are a number of things that could be added (mandatory keys,
better error reporting, string vs number issues) but you can take
it from here.

------------------------------------------

function validate (data,schema)
  for k,v in pairs(data) do
        if type(k) ~= "number" then    -- Ignore array values.
            if not schema[k] then 
                error(k .. " is not in the schema.")
            elseif type(v) ~= type(schema[k]) then 
                error(k .. " should be a " .. type(schema[k]))
            end
            if type(v) == "table" then validate(v, schema[k]) end
      end
    end
end

------------------------------------------

schema = {
    title = "Window",
    dimensions = {
        height = 1,
        width = 1
    },
    tabStops = { }
}

data = {
    title = "HyperSchnauzer Pro",
    dimensions = {
        height = 0.5,
        width = 8
    },
    tabStops = { 1, 3, 5, 7 }
}

validate(data,schema)