2

I am currently using Luajit along side Lua 5.1 and currently trying to register a function called "Wait" within the Lua C APIs. The main purpose of the function is to pause the current thread.

Example usage:

print("Working");
Wait()
print("A");

However the function does not work as expected. Here is my C++ code.

#include <iostream>
#include <Windows.h>

extern "C" {
    #include "Luajit/luajit.h"
    #include <Luajit/lua.h>
    #include <Luajit/lualib.h>
    #include <Luajit/lauxlib.h>
}


static int wait(lua_State* lua) {
    return lua_yield(lua, 0);
}

int main() {
    lua_State* lua = luaL_newstate();

    if (!lua) {
        std::cout << "Failed to create Lua state" << std::endl;
        system("PAUSE");
        return -1;
    }

luaL_openlibs(lua);
lua_register(lua, "Wait", wait);

lua_State* thread = lua_newthread(lua);

if (!thread) {
    std::cout << "Failed to create Lua thread" << std::endl;
    system("PAUSE");
    return -1;
}

int status = luaL_loadfile(thread, "Z:/Projects/Visual Studio/Examples/Lua/Debug/Main.lua");

if (status == LUA_ERRFILE) {
    std::cout << "Failed to load file" << std::endl;
    system("PAUSE");
    return -1;
}

int error = lua_pcall(thread, 0, 0, 0);

if (error) {
    std::cout << "Error: " << lua_tostring(thread, 1) << std::endl;
}

system("PAUSE");
return 0;
}

When I load up the Lua script I posted above I get the following output:

Working
Error: attempt to yield across C-call boundary
Press any key to continue . . .

I been programming in Lua for more than 4 years now. I just recently started using the C APIs and I never seen the C-call boundary error before. I did some Googling and ask friends and no one seems to be able to help me. Any idea what is wrong with my code?

The error occur when I call the lua_yield(lua, 0) function in C++.

I tried the answers of the following question and nothing seems to work.

http://stackoverflow.com/questions/8459459/lua-coroutine-error-tempt-to-yield-across-metamethod-c-call-boundary
2

1 Answer 1

2

lua_pcall does not start a yieldable coroutine. The proper function to start a coroutine is lua_resume.

1
  • Wow. I can't believe I didn't figure that out. Thank a lot.
    – Kurieita
    Mar 29, 2017 at 23:23

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.