1

I'm using sol2 (v3.3.0) in C++ to run Lua coroutines. I want to pass a Lua function to C++ and execute it as a coroutine. However, my attempts to convert sol::function to sol::coroutine are not working.

Here is a minimal example that doesn't work:

#include <sol/sol.hpp>

int main() {
    sol::state lua;
    lua.open_libraries(sol::lib::base);

    lua.set_function("run_coroutine", [](sol::function func) {
        sol::coroutine co = func;
        co();
        co();
        co();
    });

    lua.script(R"(
        function story()
            print("1")
            coroutine.yield()
            print("2")
            coroutine.yield()
            print("3")
        end

        run_coroutine(story)
    )");
}

The expected output is

1
2
3

but actually nothing is shown.

How can I correctly run the Lua function as a coroutine in C++?

1 Answer 1

0

Following the official example, I have resolved the issue myself, so I am posting the solution here.

#include <sol/sol.hpp>

int main() {
    sol::state lua;
    lua.open_libraries(sol::lib::base, sol::lib::coroutine);

    lua.set_function("run_coroutine", [&lua](sol::function f) {
        sol::thread runner_thread = sol::thread::create(lua);
        sol::state_view runner_thread_state = runner_thread.state();
        sol::coroutine co(runner_thread_state, f);

        co();
        co();
        co();
    });

    lua.script(R"(
        function story()
            print("1")
            coroutine.yield()
            print("2")
            coroutine.yield()
            print("3")
        end

        run_coroutine(story)
    )");
}

This should work now, but I’m not entirely sure why. I would appreciate it if someone with more knowledge about Lua threads could provide further insights.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.