如何使用C线程多次调用lua函数

以下代码每次在不同的部分以不同的原因崩溃。尝试了所有方法。我想能够从lua脚本中调用“sleep”,并多次调用lua函数,而无需我的C程序等待lua完成。在我的示例中,“模拟”了在位置“x = 100”和“y = 200”处以每毫秒1次的速度进行500次鼠标单击。

#include <windows.h>
#include <lua.hpp>

struct MouseClick{
    lua_State *L;
    int x, y;
};

int sleep(lua_State *L)
{
    Sleep(lua_tointeger(L, 1));
    return 0;
}

void onClicK(lua_State *L, int x, int y)
{
    lua_getglobal(L, "onClick");

    lua_newtable(L);
    lua_pushinteger(L, x); lua_setfield(L, -2, "x");
    lua_pushinteger(L, y); lua_setfield(L, -2, "y");

    lua_pcall(L, 1, 0, 0);
}

void callThread(LPVOID arg)
{
    MouseClick *m = (MouseClick*) arg;
    onClicK(m->L, m->x, m->y);
}

int main()
{
    lua_State *L = luaL_newstate();
    if (luaL_loadfile(L, "test.lua"))
    {
        printf("脚本未加载。\n");
        return 1;
    }
    luaL_openlibs(L);
    lua_register(L, "sleep", sleep);
    luaL_dofile(L, "test.lua");

    for(int i = 0; i < 500; i++, Sleep(1))
    {
        MouseClick m = {lua_newthread(L), 100, 200};
        CreateThread(0, 0, (LPTHREAD_START_ROUTINE) callThread, &m, 0, 0);
    }

    getchar();
}

Lua侧:

function onClick(c)
  print(c.x, c.y)
  sleep(3000)
end
点赞