lua-users home
lua-l archive

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


>   is = setmetatable ({ }, {
>        __index = function (_, TYPE)
>                  return function (VALUE)
>                  assert (type (VALUE) == TYPE)
>                  return VALUE
>                  end end })
> 
> and use
>    f (is.number (x), is.string (s))
> which looks a lot better, without any patching.

This is nice but creates lots of functions. Here is an alternative:

local types = {
"nil", "boolean", "number", "string", "table", "function", "userdata", "thread",
}

is = {}

for _,t in pairs(types) do
	is[t] = function (v)
			if type(v)~=t then
				error(t.." expected, got "..type(v),2)
			end
			return v
		end
end

function f() end
x=2
s="a"
s=2
f (is.number (x), is.string (s))