coroutine

resumable/yielding functions from Lua

A coroutine is a reference to a function in Lua that can be called multiple times to yield a specific result. It is a cooperative function. It is run on the lua_State that was used to create it (see thread for an example on how to get a coroutine that runs on a stack space separate from your usual “main” stack space lua_State).

The coroutine object is entirely similar to the protected_function object, with additional member functions to check if a coroutine has yielded (call_status::yielded) and is thus runnable again, whether it has completed (call_status::ok) and thus cannot yield anymore values, or whether it has suffered an error (see status()’s and call_status’s error codes).

For example, you can work with a coroutine like this:

co.lua
1
2
3
4
5
6
7
8
function loop()
	while counter ~= 30
	do
		coroutine.yield(counter);
		counter = counter + 1;
	end
	return counter
end

This is a function that yields. We set the counter value in C++, and then use the coroutine to get a few values:

coroutine_main.cpp
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#define SOL_ALL_SAFTIES_ON 1
#include <sol/sol.hpp>

#include <iostream>

int main() {
	sol::state lua;
	lua.open_libraries(sol::lib::base, sol::lib::coroutine);
	lua.script_file("co.lua");
	sol::coroutine loop_coroutine = lua["loop"];
	// set counter variable in C++
	// (can set it to something else to
	// have loop_coroutine() yield different values)
	lua["counter"] = 20;

	// example of using and re-using coroutine
	// you do not have to use coroutines in a loop,
	// this is just the example

	// we start from 0;
	// we want 10 values, and we only want to
	// run if the coroutine "loop_coroutine" is valid
	for (int counter = 0; counter < 10 && loop_coroutine; ++counter) {
		// Alternative: counter < 10 && cr.valid()

		// Call the coroutine, does the computation and then suspends
		// once it returns, we get the value back from the return
		// and then can use it
		// we can either leave the coroutine like that can come to it later,
		// or loop back around
		int value = loop_coroutine();
		std::cout << "In C++: " << value << std::endl;
	}

	return 0;
}

Note that this code doesn’t check for errors: to do so, you can call the function and assign it as auto result = loop_coroutine();, then check result.valid() as is the case with protected_function.

Finally, you can run this coroutine on another stack space (NOT a different computer thread: Lua uses the term ‘thread’ a bit strangely, as we follow its usage of the term, but it is NOT a separate thread) by doing the following:

coroutine_thread.cpp
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
#define SOL_ALL_SAFTIES_ON 1
#include <sol/sol.hpp>

#include <iostream>

int main() {
	sol::state lua;
	lua.open_libraries(sol::lib::base, sol::lib::coroutine);
	lua.script_file("co.lua");
	sol::thread runner = sol::thread::create(lua.lua_state());
	sol::state_view runnerstate = runner.state();
	sol::coroutine loop_coroutine = runnerstate["loop"];
	lua["counter"] = 20;

	for (int counter = 0; counter < 10 && loop_coroutine; ++counter) {
		// Call the coroutine, does the computation and then suspends
		int value = loop_coroutine();
		std::cout << "value is " << value << std::endl;
	}

	return 0;
}

The following are the members of sol::coroutine:

members

function: constructor
coroutine(lua_State* L, int index = -1);

Grabs the coroutine at the specified index given a lua_State*.

returning the coroutine’s status
call_status status() const noexcept;

Returns the status of a coroutine.

checks for an error
bool error() const noexcept;

Checks if an error occured when the coroutine was run.

runnable and explicit operator bool
bool runnable () const noexcept;
explicit operator bool() const noexcept;

These functions allow you to check if a coroutine can still be called (has more values to yield and has not errored). If you have a coroutine object coroutine my_co = /*...*/, you can either check runnable() or do if ( my_co ) { /* use coroutine */ }.

calling a coroutine
template<typename... Args>
protected_function_result operator()( Args&&... args );

template<typename... Ret, typename... Args>
decltype(auto) call( Args&&... args );

template<typename... Ret, typename... Args>
decltype(auto) operator()( types<Ret...>, Args&&... args );

Calls the coroutine. The second operator() lets you specify the templated return types using the my_co(sol::types<int, std::string>, ...) syntax. Check status() afterwards for more information about the success of the run or just check the coroutine object in an ifs tatement, as shown above.