Lua/Luajit:暂停当前 Lua 线程

我目前正在使用 Luajit 以及 Lua 5.1,并尝试在 Lua C API 中注册一个名为“Wait”的函数。该函数的主要目的是暂停当前线程。

使用示例:

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

但是该函数不像预期那样起作用。这是我的 C++ 代码。

#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;
}

当我加载上述 Lua 脚本时,会得到以下输出:

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

我已经使用 Lua 编程超过 4 年了。我最近开始使用 C API,之前从未遇到过 C 调用边界错误。我做了一些谷歌搜索并向朋友求助,但没有人能够帮我。我的代码有什么问题吗?

当我在 C++ 中调用 lua_yield(lua, 0) 函数时会出现错误。

我尝试了以下问题的答案,但没有什么作用。

http://stackoverflow.com/questions/8459459/lua-coroutine-error-tempt-to-yield-across-metamethod-c-call-boundary
点赞
用户646619
用户646619

lua_pcall 不能启动可挂起的协程。正确的启动协程的函数是 lua_resume

2017-03-29 23:11:22