[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: Suggestion: "usertype()" function
- From: Fabien <fleutot+lua@...>
- Date: Fri, 1 Jun 2012 17:20:35 +0200
If you mainly want to use types for type-checking, we've become convinced that type() is not the best approach. We ended up with a function checks(...), which takes n arguments, and where the n-th argument describes the expected type of the n-th argument *of the calling function*. For instance, if you want function foobar to take two strings and an optional number, you'll write:
function foobar(str1, str2, n)
checks('string', 'string', '?number')
-- rest of foobar's body
end
This is terse and readable, it can be leveraged by static code analysis tools, it's trivial to disable in production code, and there are several fallback/extension mechanisms:
- types, as returned by type(), are allowed;
- if an object's metatable contains a string in a __type field, this name is also allowed;
- if tweaking the metatable isn't an option, there's a global table associating arbitrary type names to arbitrary predicates;
- several types can be allowed, separated with a bar, e.g. checks("number|string", "?table")
- a prefix "?" makes an argument optional ("?sometype" is equivalent to, although faster and more readable than, "nil|sometype");