9

I have a problem with If statement in OpenScad. I have 4 variables

a=20;
b=14;
w=1;
c=16;

I want to check witch number is bigger a or b. And after depending who is smaller to take the value of smaller variable(in our case b < a) and to make a simple operation with c variable ( c=b-w).

I tried like this but it doesn't work.

a=20;
b=14;
w=1;
c=16;
if(a>b)
{
    c=b-w;
}

if (a<b)
{
c=a-w;
}

if (a==b)
{
c=a-w;
}

It seems logic, but in openscad as I understood you can't change the value of variable inside a If statement. What trick can I use in order to get my goal. Thank you!

Chris
  • 884
  • 2
  • 11
  • 22

3 Answers3

13

in the 3. leg you confused the assignment-operator „=“ with the equal-operator „==“ (correct if (a==b)). in your 3. leg you do the same as in the 2., so you could handle both as an „else“-leg.

Correct: assignment is not allowed in if-statement. In openscad you can use the ? operator instead:

c = a > b ? b-w : a-w;

After = follows the condition. The statement after the ? becomes the value if the condition is true, and the statement after the : becomes the value if the condition is false. Nested conditions are possible, e.g. your conditions:

c = a > b ? b-w : (a < b ? a-w : a-w);

More information in the documentation.

KetZoomer
  • 2,701
  • 3
  • 15
  • 43
a_manthey_67
  • 4,046
  • 1
  • 17
  • 28
9

OpenSCAD's variable assignment is different. You can only assign variables inside a bracket. So c = b - w will only be assigned inside the if bracket. Outside if this bracket it will still be 16. Don't ask me why. You can read more in the Documentation of OpenSCAD.

Mattis
  • 156
  • 1
  • 7
-1
c = min(c,min(a,b)/2-w);

this also solve the problem )

Chris
  • 884
  • 2
  • 11
  • 22