lua-users home
lua-l archive

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


> When is reversing the order of operands in a (built-in) commutative 
> operator useful?

Because the second operand of an opcode can be a constant. So, Lua tries
to move constants to the second operand (0<a => a<0, 2*x => x*2, etc.)


> these optimisations are rarely going to make a big
> difference, and if they do, you can do them by hand anyway.

In a tight loop, the difference can be 40%.


> There are plenty of algebras in which + isn't associative (or * isn't 
> commutative). What about implementing algebras for sets or matrices? It's 
> nice to use + and *, but the optimiser can easily mess up your program.

Both in sets and matrices '+' is associative (well, assuming + is set
union). Commutativity is more problematic, and actually is what Lua
changes most.

Maybe we could specify when Lua changes the order? (It is only in the
case that the first operand is a constant and the second is not; or it
could be ;-)


> > about  "x = a..b..c..d" and "x = a..(b..(c..d))" ?
> 
> I'd assumed that .. associates to the left, since it's the natural way to 
> build strings.

But Lua has a more efficient way to build them from the right (using the
stack), so it breaks the associativity rules. The performance difference
is huge.


> How about floating-point addition? It's not associative:

Lua never breaks parentheses. If you really want "1.0 + (eps + eps)",
keep the parentheses and Lua will respect your wish.

-- Roberto