How to call lua functions with C thread multiple times
<p>The following code crashes each time at a different part and for a different reason. Tried everything. I want to be able to call "sleep" from lua script and to call lua functions multiple times without my C program having to wait for lua finishes. In my example, I "simulate" 500 mouse clicks at position <code>x = 100</code> and <code>y = 200</code> at the speed of 1 click per millisecond.</p>

<pre class="lang-c prettyprint-override"><code>#include &lt;windows.h&gt;
#include &lt;lua.hpp&gt;

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-&gt;L, m-&gt;x, m-&gt;y);
}

int main()
{
    lua_State *L = luaL_newstate();
    if (luaL_loadfile(L, "test.lua"))
    {
        printf("Script not loaded.\n");
        return 1;
    }
    luaL_openlibs(L);
    lua_register(L, "sleep", sleep);
    luaL_dofile(L, "test.lua");

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

    getchar();
}
</code></pre>

<p>Lua side:</p>

<pre class="lang-lua prettyprint-override"><code>function onClick(c)
  print(c.x, c.y)
  sleep(3000)
end
</code></pre>