Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call a function on terminating/exiting a lua script (an atexit()/cleaning function)

Tags:

lua

Question: Is there a way to call a function when the lua script is terminated by either the system or a program which has started the script (e.g. a C program)? An atexit()/cleaning function for lua.

The situation: a external C program (call it PROG) manages a lua script (call it SCRIPT) and calls its functions, the lua script uses a separated library (.so, cal it LIB) which reserves resources which should be freed when the lua script exits. The lua script is managed (and thus terminated) by PROG which i can not alter. SCRIPT should notify LIB when it is terminated.

How can this be done? Note: i'm fairly new to lua so please also explain your answer, much appreciated :)

I'm on Linux using Lua 5.3.1


Currently this seem to work:

a = {__gc = function() print'exit function from LIB called' end}
setmetatable(a,a)

1 Answers

Check out http://lua-users.org/lists/lua-l/2001-08/msg00265.html

You may need to run lua_runprotected call to prevent a stack under flow problem.

like image 64
user1779362 Avatar answered Sep 14 '26 05:09

user1779362