5

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
  • 784
  • 10
  • 22

3 Answers3

9

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, after the „?“ what's to do if the condition is true, after the „:“ the false-leg. Nested conditions are possible, e.g. your conditions:

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

further information in documentation

a_manthey_67
  • 3,498
  • 1
  • 12
  • 22
6

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
  • 126
  • 1
  • 7
-1
c = min(c,min(a,b)/2-w);

this also solve the problem )

Chris
  • 784
  • 10
  • 22