lua-users home
lua-l archive

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


>> One problem is that the logical operators 'and' and 'or' use short-circuit
>> evaluation, which is not easy to implement efficiently for user defined
>> objects.
>
> Exaclty. In Lua, as in many other languages, 'and' and 'or' are not
> exactly operators; they are more like control structures. They do not
> generate a single opcode, but a sequence of tests and jumps.
>
> In statically typed languages, the compiler knows in advance what to
> do. For a dynamic language, once the control code is generated, it is
> hard to change it.
>

>From the original post:

> I created a class for arrays that use the arithmetic and relational operators.
> But I would like also to implement logical operators so I can write:

 d = a<b and b<c

> I defined the result of the relational operators as another array of booleans
> with the result for each element. So naturally the logical operators would have
> to return also an array of booleans.

What you need metamethods for is not `and`, `or` and `not`.  It's metamethods
for `&`, `|` and `~` (or `!`), which are not in Lua yet.  They'd be
nice to have,
being predefined for boolean and number (i.e. bit32.band, bit32,bor
and bit32.bnot)
why not binary `#` for bit32.bxor while we're about it; one day when we get an
arbitrary length `bit` library they could be defined for strings too.

Dirk