lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]

> On Dec 17, 2014, at 3:47 AM, Lev <> wrote:
> I have C program that calls various Lua scripts say 10 times a second.
> Question is that is it cheap to do luaL_newstate() and luaL_openlibs(L) and
> call the script and then lua_close(L) each time I run my Lua script, or
> shall I call luaL_newstate() and luaL_openlibs(L) at the beginning of my
> application, and call lua_close(L) when I exit?
> Or ... must I call luaL_newstate() and luaL_openlibs(L) before each script
> call?
> Thanks,
> Levente

luaL_openlibs() is (comparatively) expensive; on our reference system we can create a new raw Lua state in approx. 4us, but setting up the libraries takes about 250us. In reality if you are doing this only every 100ms then perhaps that is not too much overhead, however this depends on the speed of your platform (our reference system is a core i7 2.6GHz cpu). In addition, be aware that Lua does a “clean” close, and runs a garbage collect at close time, which can also take time depending on how much memory is to be collected.

Keeping an open Lua state would be much faster, but of course your scripts need to be aware that they will inherit the outgoing global state of the previous script. There are also a number of techniques to avoid this, such as maintaining a shadow Lua global state that can be reset at the end of the script. You might also consider if you should do a manual garbage collect after each run of the script to keep memory overhead low, if this is an issue for you.