-
Notifications
You must be signed in to change notification settings - Fork 28
The LuaCoroutine Object
The LuaCoroutine Object is the way you create coroutines in Lua. In order to create a coroutine, simply go
LuaCoroutine coru = lua.CreateCoroutine();You can also create a coroutine in Lua and pass it back. Both work.
#Running A Script
Similar to the Lua object, you can run scripts on a coroutine:
std::string result = coru.RunScript("print ('hello')");#Resuming
If a coroutine in lua yielded, you can resume execution like this:
std::string result = coru.Resume();You can only resume yielded coroutines. If you want to check if you can resume, simply call this function:
bool canResume = coru.CanResume();This function returns true if the coroutine is resumable. Otherwise, a call to Resume when this function returns false will cause errors to be returned by Resume.
#Yielding Functions
LuaCppInterface has a really interesting type of function called a Yielding Function. This is basically the same as a normal function except a Yielding Function yields after the function has finished.
LuaFunction<void()> yieldControl =
lua.CreateYieldingFunction([](){ std::cout << "Yielded!" << std::endl; });How does this work? Well, when a yielding function returns, it surrenders control back to the C++ function that called it. In other words, RunScript or Resume returns. When you call Resume, whatever the yielding function returned will be returned to the Lua script that called the function.
This is very useful for co-operative multitasking. It can also be used in handling events in event loops, or to script AIs.
One last thing we need in Lua is the ability to pass around our own objects. This is extremely important because most objects are non-trivial in nature, and sometimes a LuaTable just doesn't cut it. We need more bite than that. This is where the LuaUserdata object comes in.
Next: The LuaUserdata Object