ThePhD / sol2

Sol3 (sol2 v3.0) - a C++ <-> Lua API wrapper with advanced features and top notch performance - is here, and it's great! Documentation:
http://sol2.rtfd.io/
MIT License
4.06k stars 492 forks source link

How can I create a coroutine with yield purely in C++? #1545

Open GasimGasimzada opened 8 months ago

GasimGasimzada commented 8 months ago

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:

  1. Is there a way to use a C++ function with arguments for coroutine instead of using load function that accepts a string?
  2. How can I call a yielding function from inside a C++ function? The yielding function works when inside a string when using load but I cannot get it working with a custom function?
  3. Does calling a function co() internally perform coroutine.resume(my_thread)