[Closed] Function wont return value only OK
I have this function:
(The function should iterate through a hierachy and return the first node whos name starts with the searchstring, and exit the loop)
fn findChildren parentobj searchString =
(
letterCount = searchString.count
for o in parentobj.children do
(
if substring o.name 1 lettercount == searchString then
(
return o
)
else
(
if o.children.count != 0 do findChildren o searchString
)
)
)
My problem is that the function only returns ok and not the node (o).
I have exhausted all my ideas for solutions and would very much appreciate if anyone could shed some light on this.
Btw. how do you guys preserve the codeformatting within the
tags – my indentation allways goes down the drain.
/thanks
Your logic is flawed in the function, so the function is recursing the children correctly, but not returning anything – apart from the default “OK”.
fn findChildren parentobj searchString =
(
for o in parentobj.children do
(
print o -- test that it is working
if substring o.name 1 searchString.count == searchString then
(
--return o
)
else
(
if o.children.count != 0 do findChildren o searchString
)
)
return "Not found" -- final return if everything fails
)
Probbaly need to look at “substring o.name 1 searchString.count == searchString” and get that working happily.
Cheers,
Dave
Thinking about it… apart from the logic, it’s because the function is recursive. Even though you return from one function, the rest of the tree of function calls is still running, so the next time the function runs, the old value will be overwritten. You’d be better off appending the found children to a global or in-scope array:
fn findChildren parentobj searchString =
(
for obj in parentobj.children do
(
if findstring obj.name searchString != undefined then append arrChildren obj
else if obj.children.count > 0 do findChildren obj searchString
)
)
arrChildren = #()
findChildren $ "Tea"
arrChildren
Hope that helps,
Dave
Hi Dave,
Thanks for your answers.
I have allready ended up with the array approach, but was just wondering i that was the way to go (i think its a bit messy, but hey it gets the job done).