Prevent Lua infinite loop

前端 未结 5 1832
暖寄归人
暖寄归人 2020-12-19 02:24

I use lua interfaces to get lua support in my C# program, the worker thread will freeze if the user submits code like this

while true do end
<
5条回答
  •  星月不相逢
    2020-12-19 02:37

    I suggest handling it just like any other Lua error. In other words, threat the code above as if the user had just written

    error("Script execution has been cancelled after stalling for too long")
    

    (I'm assuming that you detect infinite loops by assuming that no script should take more than a fixed amount of time to run. Change the message appropiatedly if this is not the case)

    The way you will have to handle this will depend on how you deal with Lua errors - but you will have to do it anyway, so chances are that most of the code is there already.

    EDIT: It seems that Martin James' suggestion is your best option. You can use the debug.setHook() to run some lua code every 100 Lua instructions or so, and if too much time has passed on the same client code, throw the error. Details about this can be found on this mailing list, and code sample on the lua-project repo.

提交回复
热议问题