[OpenSCAD] got a problem with variables and setting values

Jordan Brown openscad at jordan.maileater.net
Sun Apr 29 10:38:41 EDT 2018


On 4/28/2018 7:27 PM, r.d. terramir wrote:
> here's my code I wanted to make the code parametric so I needed
> various possible  values but I hit a snag.
>
> bearings=10;
> //for smooth rods put in diameter in mm
> smooth=10;
> // for z-screw 5 for 5mm 8 for 8mm and 8.5 for acme
> z_screw=5;
> // for mechanical z=probe use 1 for yes 0 for no 2 for i3 type probe
> z_probe = 1;
> wall=4;
> lmd=1;
> lml=1;
> echo(bearings,smooth,z_screw);
> if (bearings==10){lmd=19.05;lml=29.05;}
>    echo(lmd,lml);
>
> lmd and lml return 1 even though I thought I was assigning the actual
> values with the if statement.

This might well be the most common OpenSCAD question.

OpenSCAD variables... aren't variables.  They're constants, sort of,
with the last assignment winning and with inner scopes able to override
values from outer scopes.  You can't change them, or at least not
exactly, and you especially can't change them inside an "if".

    x=1;
    echo(x=x);
    x=2;
    echo(x=x);

produces

    ECHO: x = 2
    ECHO: x = 2

and

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

produces

    ECHO: x = 1
    ECHO: x = 2
    ECHO: x = 1

For your case here, you need to use the ?: operator to set the right
value when you do the initial assignment.

    lmd= bearings==10 ? 19.05 : 1;
    lml= bearings==10 ? 29.05 : 1;
    echo(bearings,smooth,z_screw);
    echo(lmd,lml);


-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.openscad.org/pipermail/discuss_lists.openscad.org/attachments/20180429/a94be14c/attachment.html>


More information about the Discuss mailing list