Why is this function returning null?
Stretch65
Posts: 166
Hi,
I'm having trouble understanding why this code is not working. Basically I load a figure into the scene and select it.
The script is then supposed to find a bone with the word "abdomen" in it's name (and then select the bone). The function 'findBone()' appears to be working correctly,
but it keeps returning null instead of a bone. I've been staring at it until I'm cross-eyed and I still can't see why it's doing this:
(function() { var title = "Select Child Nodes", node = null, skel = null; // Find a bone containing 'str' in it's name: function findBone(parent, str) { var len = parent.getNumNodeChildren(), child = null; for (var i=0; i<len; i++) { child = parent.getNodeChild(i); print("Checking: "+child.getName()); if (child.getName().find(str) >= 0) { print(child.getName() + " found!"); return child; } findBone(child, str); } } try { node = Scene.getPrimarySelection(); if (!node) throw new Error("Select a bone in a figure"); if (node.inherits("DzSkeleton")) skel = node; else if (node.inherits("DzBone")) skel = node.getSkeleton(); else throw new Error("Select a bone in a figure"); var abdomen = findBone(skel, "abdomen"); if (abdomen) abdomen.select(true); else print("Bone Not Found!"); } catch(err) { MessageBox.critical(err.message + "\n(line: " + err.lineNumber + ")", title, "&OK" ); return false; }})()
Comments
Because you havea recursive function. Although it returns the found bone on success, it is returning it to the previous calling function and that doesn't do anything with the result. Try storing the result of the return and then if it's valid return it to the next level up:
Is the recursion really necessary? It's made more complicated by the recursive call being inside a loop too. Why not something like:
What recursion? The findBone function is defined within anotehr function but it's closing brace is the one just above the try clause, so there's no recusrion that I can see - though admittedly I do not know the Daz scripting language!
Function findBone is calling findBone.
I did it recursively just for the 'fun' of it. Thanks Richard - it's been a while since I've tried simple recursion.
That's what I was referring to. Should've been more specific.
Fair enough! Gives me the heebie-jeebies, but each to their own.
Oh heck, so it is!