强制 Lua 脚本退出 [英] Forcing a Lua script to exit

查看:51
本文介绍了强制 Lua 脚本退出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何结束长时间运行的 Lua 脚本?

How do you end a long running Lua script?

我有两个线程,一个运行主程序,另一个控制用户提供的 Lua 脚本.我需要终止运行 Lua 的线程,但首先我需要退出脚本.

I have two threads, one runs the main program and the other controls a user supplied Lua script. I need to kill the thread that's running Lua, but first I need the script to exit.

有没有办法强制脚本退出?

Is there a way to force a script to exit?

我读到建议的方法是返回 Lua 异常.但是,不能保证用户的脚本将永远调用 api 函数(它可能处于紧忙循环中).此外,用户可以通过使用 pcall 来防止错误导致脚本退出.

I have read that the suggested approach is to return a Lua exception. However, it's not garanteed that the user's script will ever call an api function ( it could be in a tight busy loop). Further, the user could prevent errors from causing his script to exit by using a pcall.

推荐答案

您可以使用 setjmplongjump,就像 Lua 库在内部所做的那样.这将使您摆脱 pcalls 和其他东西,而无需不断出错,防止脚本尝试处理您的虚假错误并仍然使您无法执行.(不过我不知道这对线程的作用如何.)

You could use setjmp and longjump, just like the Lua library does internally. That will get you out of pcalls and stuff just fine without need to continuously error, preventing the script from attempting to handle your bogus errors and still getting you out of execution. (I have no idea how well this plays with threads though.)

#include <stdio.h>
#include <setjmp.h>
#include "lua.h"
#include "lualib.h"
#include "lauxlib.h"

jmp_buf place;

void hook(lua_State* L, lua_Debug *ar)
{
    static int countdown = 10;
    if (countdown > 0)
    {
        --countdown;
        printf("countdown: %d!
", countdown);
    }
    else
    {
        longjmp(place, 1);
    }
}

int main(int argc, const char *argv[])
{
    lua_State* L = luaL_newstate();
    luaL_openlibs(L);
    lua_sethook(L, hook, LUA_MASKCOUNT, 100);

    if (setjmp(place) == 0)
        luaL_dostring(L, "function test() pcall(test) print 'recursing' end pcall(test)");

    lua_close(L);
    printf("Done!");
    return 0;
}

这篇关于强制 Lua 脚本退出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆