【问题标题】:Lua/Luajit: pause current Lua threadLua/Luajit:暂停当前 Lua 线程
【发布时间】:2017-08-23 14:51:48
【问题描述】:

我目前正在与 Lua 5.1 一起使用 Luajit,目前正在尝试在 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

【问题讨论】:

标签: c++ lua luajit


【解决方案1】:

lua_pcall 不会启动可屈服的协程。启动协程的正确函数是lua_resume

【讨论】:

  • 哇。我不敢相信我没有弄清楚。非常感谢。
猜你喜欢
  • 2015-06-04
  • 1970-01-01
  • 2017-11-07
  • 2023-03-11
  • 2013-09-23
  • 1970-01-01
  • 2022-07-14
  • 1970-01-01
  • 2016-09-01
相关资源
最近更新 更多