2

I'm try to compile this .less code to .css via lessphp and get this error:

Fatal Error:
====================
infinite loop detected: @pos-x: failed at `background-position: @pos-x 0; }` line: 3

Here is my code.

@pos-x : 0;
@w : 30px;
.a { background-position: @pos-x 0; }

@pos-x: @pos-x - @w;
.b { background-position: @pos-x 0; }

What's wrong with it? Can i use varable overriding in LESS?

Love Senya
  • 23
  • 2

1 Answers1

2

@pos-x: @pos-x - @w; is not allowed. The documentation states, "Note that variables in LESS are actually ‘constants’ in that they can only be defined once."

I believe what happens with LESS in such a case is essentially this:

@pos-x: 0;
@pos-x: @pos-x - 30px; puts it into this loop...
        @pos-x = -30px - 30px ...
        @pox-x = -60px - 30px ...
        @pox-x = -90px - 30px ... etc.

Thus, it continually recalculates the @pos-x trying to come to a final resolution which is never reached. Everytime it is reassigned, it attempts to reevaluate based off that new assignment.

So do something like this:

@pos1-x : 0;
@w : 30px;
.a { background-position: @pos1-x 0; }

@pos2-x: @pos1-x - @w;
.b { background-position: @pos2-x 0; }
ScottS
  • 71,703
  • 13
  • 126
  • 146
  • Intentional or not, lessPHP actually allows variables to be redefined - although it does compute the actual (last declared) value before applying it. In any case, this is still a correct answer. – Wesley Murch Dec 17 '12 at 18:09
  • You can paste this into the [online compiler](http://leafo.net/lessphp/) to see it: `@base: #fff; @base: @base; p{color:@base}` – Wesley Murch Dec 17 '12 at 18:15
  • @WesleyMurch: Yes, I have questioned before what they have meant by that statement, as one can "redifine" (overwrite) a variable in LESS. But I think this case here is perhaps part of what they intended to communicate. – ScottS Dec 17 '12 at 18:15
  • Right, for example (at least with lessPHP), this: `@c: #fff; p {color:@c} @c: #000;` produces the CSS `p { color: #000; }` – Wesley Murch Dec 17 '12 at 18:16
  • Right, the first piece of code was meant to demonstrate the loop and your correct-ness. The second was meant to demo "redefining variables" behavior. – Wesley Murch Dec 17 '12 at 18:17
  • @WesleyMurch: your first code gives the infinite loop error on that compiler. – ScottS Dec 17 '12 at 18:23
  • @WesleyMurch: Okay! We are on the same page then. – ScottS Dec 17 '12 at 18:23