added turtles to concepts

This commit is contained in:
Niklas Kapelle 2024-01-22 23:37:02 +01:00
parent 22509932c3
commit e2916a213a
Signed by: niklas
GPG Key ID: 4EB651B36D841D16

View File

@ -120,3 +120,39 @@ In order for you program to be used it needs to be registered in the `BinStore`
You can imagine the whole runtime like the event loop is JS. The `EndOfLoop` class is used to register callbacks that are called at the end of the loop. You can imagine the whole runtime like the event loop is JS. The `EndOfLoop` class is used to register callbacks that are called at the end of the loop.
This is like the `setTimeout(0, callback)` in JS. This is like the `setTimeout(0, callback)` in JS.
# Turtle Thread
Computercraft is mostly event-based. Listening to `Coroutine.yield()` waits for events with an option parameter for filtering events.
The problem with turtle arises when we call turtle functions like `move` or `place`. These functions wait internally for
the operation to finish with a `Coroutine.yield("turtle_response")` call. There is no way to prevent this. So in order to keep the main loop from
being blocked, we run all the turtle code in a separate thread.
There are no real threads in Lua, but we can create a coroutine for the turtles. Lua now switches between the main thread and the turtle thread.
Switching occurs when a `turtle_response` events is fired. This will be forwarded to the turtle thread. Once the turtle thread has run its code
and waits for the turtle operation to finish, we switch back to the main thread. The main thread is running normally until a `turtle_response` fires
and the circle repeats.
Be aware that no one is stopping you from running turtle commands in the main thread.
See `KernelEvents.hx` for more.
## Using Turtle threads
Example:
```haxe
// In the context of a process
if (!handle.claimTurtleMutex()) {
Log.warn("Failed to claim turtle thread");
return;
}
// Btw. no one is stopping you from calling this without claiming the mutex.
TurtleMutex.runInTThread(() -> {
while(true){
Turtle.turnLeft();
}
});
```