lua-users home
lua-l archive

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

On Wednesday, November 20, 2013, Philipp Janda wrote:
Am 20.11.2013 23:24 schröbte Andrew Starks:

What do you think about  something like `getudtype(userdatavalue)`,
where the field name from the registry or something like a __type
field value would be returned.

Again, easy to add if you've got debug. I find that as a Lua user,
knowing the *kind* of userdata that I'm holding is sometimes relevant.

What for? You are not accessing the userdata's memory directly from Lua so you don't *need* the actual userdata type for type safety, and if you check for it anyway you run into the same issues as with function/is_callable, i.e. you lose the ability to pass e.g. a mock object instead of the real thing (or an object "writing" to an array instead of a real file object) ...


There are many times that I've run into this and I am sincerely open to alternate approaches...

I'm parsing input from LPEG. I'm working with both int64 and a real number (media_time / media_scale). What is int64, realnum or LPEG? All are userdata. All are happy with -+/*. Most often I get an error. Sometimes I don't. 

Also, functions in Lua work like you describe (mostly). Many C functions called by Lua don't. There is no "tonumber" that the math library calls, so I end up wrapping that up. 

As a convenience, whenever I call `type(v) == "userdata"`, it strikes me that, as a Lua user, I never care if it's really a "userdata."  At that point, I've designed program such that I'm checking for a particular kind of userdata so that I can take some sort of exceptional action to do whatever is needed to get it into whatever I was expecting or, more likely, whatever some other library expects.

Userdata often has metamethods beyond __call, including +*/ etc. so long as that's the case, there will be ligitamate times where knowing the true type of a userdata value results in the clearest, simplest code.