gudzpoz / luajava

Lua for Java on Windows, Mac OS X, Linux, Android. 5.1, 5.2, 5.3, 5.4, LuaJ or LuaJIT.
https://gudzpoz.github.io/luajava/
Other
151 stars 19 forks source link

Green-Threads (Cooperative threading) #140

Closed orange451 closed 10 months ago

orange451 commented 10 months ago

Hey! I wanted to embed lua in to a project of mine, but I have a requirement that I want to see if this library can meet. I want to be able to have multiple scripts execute cooperatively. This means that they are running on the same thread and sharing the same context, but maintain their own stacks (local variables, functions, etc).

Here is an example scenario:

-- Script 1
print("Hello From Script 1")
wait(5)
print("Finished 1")
-- Script 2
wait(1)

print("Hello From Script 2")
wait(5)
print("Finished 2")

Obviously wait() is a method that I would have to design and build a scheduler for. But I would want these two scripts to be able to run at the same time. The desired output would be:

> Hello From Script 1
> Hello From Script 2
> Finished 1
> Finished 2
gudzpoz commented 10 months ago

Actually, Lua itself supports this via its builtin coroutine library, with a few caveats though:

  1. I don't think the scripts can literally "run at the same time" since Lua does not guarantee OS-thread safety. (But you've mentioned that "they are running on the same thread" so it is probably fine to you?)
  2. Yes, you will need to write a scheduler yourself. There seems to be existing libraries for that (like https://github.com/lukashoracek/lua-scheduler or https://gist.github.com/saga/3662845 ), which you can adapt from.

See 9.1 – Coroutine Basics - PIL.