| 5 | #include <iostream> |
| 6 | |
| 7 | int main() { |
| 8 | std::cout << "=== coroutine ===" << std::endl; |
| 9 | |
| 10 | sol::state lua; |
| 11 | std::vector<sol::coroutine> tasks; |
| 12 | |
| 13 | lua.open_libraries(sol::lib::base, sol::lib::coroutine); |
| 14 | |
| 15 | sol::thread runner_thread = sol::thread::create(lua); |
| 16 | |
| 17 | lua.set_function("start_task", |
| 18 | [&runner_thread, &tasks]( |
| 19 | sol::function f, sol::variadic_args va) { |
| 20 | // You must ALWAYS get the current state |
| 21 | sol::state_view runner_thread_state |
| 22 | = runner_thread.state(); |
| 23 | // Put the task in our task list to keep it alive |
| 24 | // and track it |
| 25 | std::size_t task_index = tasks.size(); |
| 26 | tasks.emplace_back(runner_thread_state, f); |
| 27 | sol::coroutine& f_on_runner_thread |
| 28 | = tasks[task_index]; |
| 29 | // call coroutine with arguments that came |
| 30 | // from main thread / other thread |
| 31 | // pusher for `variadic_args` and other sol types |
| 32 | // will transfer the arguments from the calling |
| 33 | // thread to the runner thread automatically for |
| 34 | // you using `lua_xmove` internally |
| 35 | int wait = f_on_runner_thread(va); |
| 36 | std::cout << "First return: " << wait |
| 37 | << std::endl; |
| 38 | // When you call it again, you don't need new |
| 39 | // arguments (they remain the same from the first |
| 40 | // call) |
| 41 | f_on_runner_thread(); |
| 42 | std::cout << "Second run complete: " << wait |
| 43 | << std::endl; |
| 44 | }); |
| 45 | |
| 46 | lua.script( |
| 47 | R"( |
| 48 | function main(x, y, z) |
| 49 | -- do something |
| 50 | coroutine.yield(20) |
| 51 | -- do something else |
| 52 | -- do ... |
| 53 | print(x, y, z) |
| 54 | end |
| 55 | |
| 56 | function main2(x, y) |
| 57 | coroutine.yield(10) |
| 58 | print(x, y) |
| 59 | end |
| 60 | |
| 61 | start_task(main, 10, 12, 8) |
| 62 | start_task(main2, 1, 2) |
| 63 | )"); |
| 64 |
nothing calls this directly
no test coverage detected