Welcome to the Onshape forum! Ask questions and join in the discussions about everything Onshape.
First time visiting? Here are some places to start:- Looking for a certain topic? Check out the categories filter or use Search (upper right).
- Need support? Ask a question to our Community Support category.
- Please submit support tickets for bugs but you can request improvements in the Product Feedback category.
- Be respectful, on topic and if you see a problem, Flag it.
If you would like to contact our Community Manager personally, feel free to send a private message or an email.
Can someone explain new box()?
I see new box()
used in the std and other places by people who are better at coding than me, but still haven't wrapped my head around it or when I'd want to use it. I've read the explanation here in the FS documentation, and AI says to use Box Types "When you need to wrap a single value and potentially add additional metadata or behavior or for implementing generic programming patterns", but I'm still not clear on it. Anyone care to explain it a bit or link me to a good primer?
Best Answer
-
ilya_baran Onshape Employees, Developers, HDM Posts: 1,215
Boxes are a way around the issue that FeatureScript values are generally unchangeable — if you have:
var x = { a : 12 }; myFunction(x); println(x);
You'll always see
{a : 12}
no matter whatmyFunction
does. (It does not work this way in Java or JavaScript, for example).If you want a function to be able to change an argument, you need to put it in a box, like this:
var x = new box({ a : 12 }); myFunction(x); println(x[]); … // In myFunction: x[] = 3;
Then this code will print
3
becausemyFunction
changed "what is in the box".This can lead to useful patterns like the pseudo random number generator I posted here:
Hope this helps.
Ilya Baran \ VP, Architecture and FeatureScript \ Onshape Inc2
Answers
Boxes are a way around the issue that FeatureScript values are generally unchangeable — if you have:
You'll always see
{a : 12}
no matter whatmyFunction
does. (It does not work this way in Java or JavaScript, for example).If you want a function to be able to change an argument, you need to put it in a box, like this:
Then this code will print
3
becausemyFunction
changed "what is in the box".This can lead to useful patterns like the pseudo random number generator I posted here:
Hope this helps.
oooh! Thanks Ilya, that made it click. Lots of possibilities.