Workaround for odd variable behaviour?

classic Classic list List threaded Threaded
3 messages Options
Reply | Threaded
Open this post in threaded view
|

Workaround for odd variable behaviour?

Troberg
This code, which in most languages would result in 1 being output, results in
a 0.

 x=0;
 y=true;
 
 if(y==true){
  x=1;
 }else{
  x=2;
 }
 echo(x);

This, I understand, is because the x in the if only exist within that scope.
I can understand that.

However, it's extremely frustrating that I can't find a good way to get the
behaviour I want. Sometimes, it would be extremely useful to be able to set
a variable in an if, and then use it later, to avoid having to duplicate
(and, in the case of multiple variables, even more sets of copied code)
large blocks of code. I could break out the code blocks into modules, and
then call them, but I try to use modules where they are a logical block, not
just to reduce lines.

Any suggestions?



--
Sent from: http://forum.openscad.org/

_______________________________________________
OpenSCAD mailing list
[hidden email]
http://lists.openscad.org/mailman/listinfo/discuss_lists.openscad.org
Reply | Threaded
Open this post in threaded view
|

Re: Workaround for odd variable behaviour?

atnbueno
Does this help?

y = true;
x = y ? 1 : 2;
echo(x);


2017-10-28 11:18 GMT+02:00 Troberg <[hidden email]>:
This code, which in most languages would result in 1 being output, results in
a 0.

 x=0;
 y=true;

 if(y==true){
        x=1;
 }else{
        x=2;
 }
 echo(x);

This, I understand, is because the x in the if only exist within that scope.
I can understand that.

However, it's extremely frustrating that I can't find a good way to get the
behaviour I want. Sometimes, it would be extremely useful to be able to set
a variable in an if, and then use it later, to avoid having to duplicate
(and, in the case of multiple variables, even more sets of copied code)
large blocks of code. I could break out the code blocks into modules, and
then call them, but I try to use modules where they are a logical block, not
just to reduce lines.

Any suggestions?



--
Sent from: http://forum.openscad.org/

_______________________________________________
OpenSCAD mailing list
[hidden email]
http://lists.openscad.org/mailman/listinfo/discuss_lists.openscad.org



--
Saludos,
Antonio



_______________________________________________
OpenSCAD mailing list
[hidden email]
http://lists.openscad.org/mailman/listinfo/discuss_lists.openscad.org
Reply | Threaded
Open this post in threaded view
|

Re: Workaround for odd variable behaviour?

Troberg
Yep, that worked! Didn't know about the trinary if operator, I just kept
looking for an iif function. Thanks!



--
Sent from: http://forum.openscad.org/

_______________________________________________
OpenSCAD mailing list
[hidden email]
http://lists.openscad.org/mailman/listinfo/discuss_lists.openscad.org