lua-users home
lua-l archive

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


With a metatable and some helper functions, you can have almost what you need :

local function required(msg)
  return function(value) return value or error(msg, 2) end
end
local function check_type(...)
  local types = {...}
  return function(value)
    local t = type(value)
    for i=1,#types do
      if t == types[i] then return value end
    end
    error("Expected value of type "..table.concat(types, " or ")..", got "..t)
  end
end
function get_args(args, canvas)
  return setmetatable({}, {__index=function(t, k)
    local v = rawget(canvas, k)
    if type(v) == 'function' then return v(args[k]) end
    return args[v] or v
  end})
end


Function get_args must be called at the beginning of all named
parameters functions.
Local functions required and check_type are just example of validating
functions.
With that above code, you can then write something like this:

function person(args)
  args = get_args(args, {
    name = required "Please provide a name", -- your name
    age = check_type("number"), -- your age
    address = "(no street address)", -- your street address
   })

   print(args.name, args.age, args.address)
end

person{name = "John Doo", age=56}
--> John Doo 56  (no street address)
person{}
-- Error: Please provide a name