Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
383 views
in Technique[技术] by (71.8m points)

c++ - How can I end a Lua thread cleanly?

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 essential if the script contains an infinite loop), how can I do this?

lua_State *Lua = lua_open();
char * code;
// Initialisation code
luaL_dostring(L, code);
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...