Welcome! Log In Create A New Profile

Advanced

conditional assignment

Posted by appjaws1 
conditional assignment
December 09, 2016 12:52PM
I have been using:-
fan_mount_dist = (fan_width == 50) ? 40 : 32;

which will assign 40 to fan_mount_dist if fan_width=50 else it will assign 32 to fan_mount_dist.

What I need to do is have a selection of 4 items(32,40,02,70 which will depend on the value of fan_width of 40,50,60,80.

any ideas how to accomplish this?


appjaws - Ormerod 1, core XYUV Duet wifi, duex5
firmware 1.21 Web Server 1.21 Web Interface 1.21
OpenSCAD version 2016.02.09 (git 9950e6a)
slic3r-1.38.5-prusa3d and/or Simplify3D 4.0.0
Re: conditional assignment
December 09, 2016 04:54PM
You could of course use several nested (?smiling smiley operators, but the code would become long and difficult to read...
A recursive function like the lookup() function below is probably easier and can be used for as many value pairs as needed:


function lookup(v,var,lar,i=0) = (var[ i ]==v) ? lar[ i ] : ( i < len ( var ) ? lookup( v, var, lar, i + 1 ) : -1);

fanmount_dist = lookup(fan_width, [40,50,60,80], [32,40,02,70]);



Note that if the given fan_width value is not found, lookup() will return the value -1.

Edited 7 time(s). Last edit at 12/10/2016 02:17AM by enif.
Re: conditional assignment
December 09, 2016 09:48PM
enif,
thank you very much, just what I'm looking for.

I think I might be doing something wrong because I can not get your code to work.
There seems to be an extra ")" on the last line and when I remove it the code compiles but no matter what I set fan_width to I only get -1 returned

So I am stumped, it's probably easily rectified but I just don't have the skills to spot the error.


appjaws - Ormerod 1, core XYUV Duet wifi, duex5
firmware 1.21 Web Server 1.21 Web Interface 1.21
OpenSCAD version 2016.02.09 (git 9950e6a)
slic3r-1.38.5-prusa3d and/or Simplify3D 4.0.0
Re: conditional assignment
December 10, 2016 02:30AM
Ok, I found the problem: The forum software "mangled" the program lines. I knew that this happens sometimes in code section by adding unwanted smileys, but this time it ate up the indices and the square brackets of the lar and var arrays. In the edit window and even in the preview window all shows correctly, but then one submitted, the message gets mangled. So I had to do a lot of trial an error editing added unneeded blanks until I finally found a way which seems to show up correctly in the message thread... Let's hope it now works for you.
Sorry, only registered users may post in this forum.

Click here to login