How can I end a Lua thread cleanly?

前端 未结 2 1027
青春惊慌失措
青春惊慌失措 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:42

    Hook on lines is not enough. This code is a single line, but loops forever:

        while true do end
    

    You need to set an instruction count hook. If I'm not mistaken, that would be

        lua_sethook(Lua, &LineHookFunc, LUA_MASKCOUNT, NUM_INSTRUCTIONS);
    

    You want to pick NUM_INSTRUCTIONS so it is not too small (or you get a performance overhead) and not too large (or you'll wait too long until stop).

    For related Lua-only implementation please see this library.

    If you want to add more protection from untrusted Lua code, google for "Lua sandboxing" -- there is more to it than just infinite loop prevention.

提交回复
热议问题