How can I end a Lua thread cleanly?

前端 未结 2 1028
青春惊慌失措
青春惊慌失措 2020-12-16 07:14

My situation is that I\'m using the Lua (C) API to execute a script held in a string. I would like the user to be able to terminate the execution of the script (this is esse

2条回答
  •  清歌不尽
    2020-12-16 07:44

    You can use a hook to callback to C every time lua executes a line of the script. In this hook function you can check if the user wanted to quit, and call lua_error if they did.

    static bool ms_quit = false;
    
    void IWantToQuit()
    {
        ms_quit = true;
    }
    
    void LineHookFunc(lua_State *L, lua_Debug *ar)
    {
        if(ar.event == LUA_HOOKLINE)
            if(ms_quit == true)
                luaL_error(L, "Too Many Lines Error");
    }
    //...
    
    lua_State *Lua = lua_open();
    char * code;
    // Initialisation code
    lua_sethook(Lua, &LineHookFunc, LUA_MASKLINE, 0);
    luaL_dostring(L, code);
    

提交回复
热议问题