lua-users home
lua-l archive

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



On Wed, Nov 19, 2014 at 12:13 PM, Dirk Laurie <dirk.laurie@gmail.com> wrote:
io.type (obj)

Checks whether obj is a valid file handle. Returns the string "file" if obj is
an open file handle, "closed file" if obj is a closed file handle, or nil if obj
is not a file handle.

This being the closest example, in that math.type returns the number's subtype, which would be one of two answers. In the case of LPEG, there is only ever one answer (or nil or error, i don't know which).

As an exercise in understanding, I'll summarize: 

Lua values have a basic type, aka 'type', which can be discovered by using the `type` library function, which returns a string of the type's name.

By loose convention, we have subtypes, in that some userdata and some people's libraries use a "type" field in their object-like structures. In those examples, the collection of methods (class) takes an object as the first argument to its method called "type", such that `obj:type()` or `library_name.type(obj)` yields the specific subtype.

Numbers also have a subtype, however there is no `number` library, and so the  `math.type` method is used, instead. Since you rarely need to be bothered with this sort of thing and `math` and `number` are close enough, there would be little point in making one for just this method.

Also, in the case of using this in your own software, adhering to convention requires that your "subtype" is not a hash, or that `type` is reserved and `pairs` should be patched accordingly. This is also fine since subtypes are not needed very often and the need for a language-level facility like this is even less. Variations on this approach may be used when the norm fails you.

This means that, for a simple use case, you might do something like:

```
if type(foo) == "userdata" and foo.type and foo.type() == "my_type" then
   --do stuff here
end
```
For a more complex use case, it's the same but more.

--------

The above scenario is so common in Lua that it becomes transparent. What I mean is that, I avoid it, work around it, do things in other ways, don't check types, infer types by looking for values, make my own 'subtype` system or... whatever. So, it's not a real problem. 

BUT, if there was a more formalized, elegant and Lua-esque way to do this, that was at the language level instead of the "loose convention" level (you may choose to take issue with 'loose'), I don't know that things would not be improved. 

In the case of numbers/integers/integrals/floats, it hasn't mattered to me, very often. It may later. It may matter to a significant number of other people. I don't wish any of the above to be interpreted as an argument for change. 

All features have costs.

-Andrew