lua-users home
lua-l archive

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

Am 24.07.2013 06:41 schröbte Miles Bader:
Thijs Schreijer <> writes:
Then I would rather have a single type() function and replace its
number' return value with the new types. Big incompatibility but the
new integer division operator already is. Incompatible but clean.

Predicates are actually _more_ clean, and yet aren't incompatible
("isnumber" and "isinteger"/"isfloat" can exist simultaneously).

If you are worried about function namespace pollution (I'm not,
particularly, but ...), it's also possible to use a predicate-style
solution with a separate type namespace, e.g. "istype(OBJ, TYPE)",
where TYPE is 'number', 'float', 'table', etc.

How about a compromise:

If called like this:

    type( v )

the `type` function returns one of the eight basic type names like it is now.
If called with extra string arguments:

    type( v, "integer" )

it returns the first extra string argument that matches the type of the value, or nil if none matches.

This way we can use it as predicate for overlapping types:

   if type( v, "float" ) then ... end

and still dispatch on the type:

   callbacks[ type( v ) ]( x, y, z )

and even combine those two methods:

   callbacks[ type( v, "callable", "indexable" ) or type( v ) ]( x, y, z )

But I think the reason to introduce type predicates (virtual types such as "callable") is a reason to *not* use them for the integer/float distinction: there may be other objects that implement float-like or integer-like interfaces, and we would still have the same problem as with functions and is_callable ...

IMHO, virtual types would be better handled with something like:

has"__index,__newindex,__len,__ipairs"( v ) --> array-like type or table
   has"__call"( f )   --> callable type or function

with some additional logic to handle the predefined capabilities of numbers, strings, tables, and functions.