[Date Prev][Date Next][Thread Prev][Thread Next]
- Subject: Re: Constant folding
- From: Mike Pall <mikelu-0603@...>
- Date: Tue, 14 Mar 2006 20:18:11 +0100
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)'
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.