lua-users home
lua-l archive

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

You know how we (well, I) keep saying that Javascript has almost
identical semantics to Lua? Well, unfortunately that's not the case. I'm
trying to port a program in Javascript to Lua that's making extensive
use of some of these semantics and I'm not sure how to emulate them.

There's two so far that are biting me:

(a) the Javascript special values undefined and null are type compatible
with numbers, so (0 > null) is valid (and false)

assert(value == undefined)
assert(!((value < 0) || (value > 0) || (value == 0)))

(b) all objects (except undefined and null) have prototypes, which means
that all objects (except undefined and null) can have their properties
accessed, including functions and numbers

assert(value == 0)
assert( == undefined)

I think I can work around (a) by creating special Lua values UNDEFINED
and NULL which are tables, and using their metatables to override all
the various arithmetic operations to return the right result. But I'm
not sure about (b).

The obvious approach here to use metatables, but Lua doesn't really
admit to having metatables for numbers... but this appears to work:

t = { __index = function() return nil }
debug.setmetatable(0, t)
value = 0
-> nil

Note that I say 'appears to work'. Is it actually working? If I take
this route, what horribleness is going to appear down the line to bite
me? Is there anything else I can do?

┌─── ───── ─────
│ "People who think they know everything really annoy those of us who
│ know we don't." --- Bjarne Stroustrup

Attachment: signature.asc
Description: OpenPGP digital signature