This is a read-only snapshot of the ComputerCraft forums, taken in April 2020.
vincoreprograms's profile picture

Help with my Program

Started by vincoreprograms, 29 December 2014 - 05:18 PM
vincoreprograms #1
Posted 29 December 2014 - 06:18 PM
So I'm working on this program and I have for the past day and I'm almost done and I want to release it by today and I wonder if anyone can help me out with this final problem.

Problem:
When the computer receives the message it duplicates into several message. If anyone can help me out that would be great!

Pastebin:
www.pastebin.com/gFfr4jkU
Bomb Bloke #2
Posted 31 December 2014 - 01:18 AM
When a function calls another function, the original function isn't thrown out of memory - instead, the Lua VM simply pauses it at that point, while it waits for the new function call to finish and return. Once that happens, the original function then carries on from where it left off.

Let's say, for example, that we do this:

function moo()
  moo2()
end

function moo2()
  moo()
end

moo()

moo() will call moo2(), which will call moo(), which will call moo2(), etc. Because none of these function instances are ending, but rather are simply opening up new function calls, the memory Lua reserves for tracking all these active functions (the "stack") gets flooded and the script will error out due to the resulting stack "overflow".

In your script, never allowing your functions to end results in additional complications, due to your use of parallel.waitForAny(listen, mouse_main). When you first run that command, you've then got your listener function running alongside your mouse_main function. After you send an email or something, the thread you assigned mouse_main to ends up starting listen and mouse_main in parallel again - but the other thread's still running listen as well, so now you've got two listen functions being alternatively activated by the parallel API. Send another email, and it's three.

Since each of these functions are being activated in turn (thanks to the parallel API) and are passed copies of all events (again thanks to the parallel API), the more instances of the listen function you dump into the stack, the more duplicates of each incoming message you'll receive when one eventually comes through. At that point all of the listen functions do end, and so the stack collapses back down (as parallel.waitForAny() kills all co-routines it's managing once any one of them finishes).

In short, in order to prevent this build-up, you need to re-write the flow of the entire program so that your functions are allowed to end. In order to do this, you need to make frequent use of the "return" statement (so that your functions can pass information back to their callers) - see this tutorial if you're unfamiliar with it.
vincoreprograms #3
Posted 31 December 2014 - 03:25 AM
Thanks Bomb Bloke! It's much appreciated that you took the time to look through my errors.