lua-users home
lua-l archive

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



On Sun, Feb 22, 2009 at 12:34 PM, David Given <dg@cowlark.com> wrote:
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)

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

As far as I know there's very little you can do about this except wrap every "if" condition and "and"/"or" operand in a call to this:

local function jstrue(n)  return (n and n ~= 0);  end

...ugly - and will also break if you want (a || b) to return zero when a is false and b is zero, as the conversion (jstrue(a) or jstrue(b)) will evaluate to false.

(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

(_javascript_)
assert(value == 0)
assert(value.property == 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:

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

Note that I say 'appears to work'. Is it actually working?

Yes, absolutely. Lua supports numbers having a shared metatable just as well as it does strings having a shared metatable, which of course they do for ("HELLO"):lower() to work like string.lower("HELLO"). Numbers just happen not to have one, in a standard Lua instance.

-Duncan