ID:1292236
 
Just searching for some clarification here, I would like to know what happens under the hood for the following code:

proc/test_while()
while(1)
x++
sleep(1)


vs

proc/test_spawn()
x++
spawn(1) test_spawn()


It is my understanding that the test_while() will never return, but test_spawn() will return after every spawn(1) call. test_spawn() is scheduling a new call every 10th second but is also returning within the tick its called. Also, the object that test_while() belongs to can't be garbage collected unless there's a break case or a return.

I would like to know a little more about the stack specifically. I've tested situations where recursive spawn() is actually more efficient than while() which is strange considering I think spawn() should have more overhead with the constant stacking.

It is not clear to me when to choose to use one method over the other.
or
proc/test_label()
huh
x++
goto huh
Well if you think about a while statement you have things like:

proc call
while
code
increment
while again

where as with your spawn you have

proc call
increament
proc call

So in your example you have less steps in your second method, but could it cause errors, very possibly as there is not a way to not call test_spawn().

From a computer science standpoint, (I think) loops are almost always more efficient, unless you're dealing with things like nodes and trees. The latter almost always require recursion, or a mix of the two.

Really, anything you can do with recursion in DM (aside from those more comp-sci topics), you can do with looping.

If your specific use case is just an infinite background proc; go for the while loop. If you're concerned about garbage collection; just in the while() condition, check if the object has a loc:
proc/test_while() //assuming this belongs to an object
while(src.loc && !other && conditions || some || optional || !too)
x++
sleep(1)
I would still like to know, by way of a list, how the call stack works and maybe some explanation of the pros and cons of each method.
In response to Zohan98
This would result in an infinite loop and be terminated unless it has set_background = 1 at the beginning of the proc.
In response to Konlet
Konlet wrote:
This would result in an infinite loop and be terminated unless it has set_background = 1 at the beginning of the proc.

Nope. It wouldn't terminate. It would automatically switch it to background. The error actually says:"
Infinite loop suspected--switching proc to background.
If it is not an infinite loop, either do 'set background=1' or set world.loop_checks=0."

To avoid getting the error; all you'd really do is add a delay via sleep().

However, it's still bad programming. There is rarely a good case to use goto.