lua-users home
lua-l archive

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


Mike Pall wrote:
Kein-Hong Man wrote:
It is not heavy-duty constant folding, though. According to my observations, the terms of an expression are not reordered, so the following is not optimized:

  local a = a+1+2

since it is parsed as:

  local a = (a+1)+2

It would violate the language semantics to optimize this at
compile time. '+' is left-associative in Lua. If 'a' is a table
or userdata with an __add metamethod, it could completely change
the execution path when the terms are reordered or folded.

It even makes a difference with numbers (lua_Number = double):

$ lua -e 'local x=2^53; print((x+1+1)-x, (x+2)-x)'
0       2

Addition is only associative in specific (mathematical) groups.
E.g. for numbers with arbitrary precision or fixed precision
integers with wrap-around semantics. Floating-point numbers with
a fixed precision do not follow this rule (and many others).

Compiler writers sometimes forget about this (hint: check your
favourite language). But Lua gets it right.

Good call. Thanks for the explanation, I was thinking in terms of integers. There is of course always a danger with shortcuts when dealing with floating-point formats. I've been applying C thinking to this thing... :-) Semantically, of course it is wrong. But in the real world, the user usually wants 1+2 optimized.

I guess the best way is to make it explicit, i.e. write:

  local a = a+1+2

as:

  local a = a+(1+2)

--
Cheers,
Kein-Hong Man (esq.)
Kuala Lumpur, Malaysia