sol2
sol2 copied to clipboard
How can I create a coroutine with yield purely in C++?
I am trying to create coroutines/threads in C++ but I cannot get it working when using C++ functions vs load method with custom string:
hello_fn = get_entity_value("e2", "hello")
The get_entity_value is a wrapper function around a coroutine to provide an easy to use API:
state.open_libraries(sol::lib::base, sol::lib::coroutine);
auto thread = sol::thread::create(state);
auto ts = thread.state();
// I want to change this to a C++ lambda function
// Ideally, I do not want the function to be in global scope
// as it is an internal implementaion detail.
sol::coroutine co = ts.load(R"(
print("Before")
coroutine.yield()
print("After")
)");
state["get_entity_value"] = [&co](Entity e, std::string name) -> sol::object {
co();
return sol::nil;
};
state.safe_script_file(filename.string());
There are couple of things that are not clear to me with Sol when it comes to coroutines:
- Is there a way to use a C++ function with arguments for coroutine instead of using
loadfunction that accepts a string? - How can I call a
yieldingfunction from inside a C++ function? The yielding function works when inside a string when usingloadbut I cannot get it working with a custom function? - Does calling a function
co()internally performcoroutine.resume(my_thread)