my question is: how to implement something like thread local storage using Lua stack (lua_State)? Some value that will be stored in the lua state, accessible to lua scripts and from C API.
1 Answer
There are several ways to do this. I wrote a paper about it; it's Chapter 1 in Lua Programming Gems
The easiest way may be to create a table in the registry whose keys are lua_States and values are your thread local data. Make the table weak in the keys so when threads are collected the thread local data is freed.
If your thread local data is only needed for, and accessed from your C library, you can instead keep a similar table in a shared upvalue of the functions of the library. Use luaL_setfuncs to register the functions with the shared upvalue table. The advantage of using this technique is that the thread local data are private to your C library.
foo='bar','bar'is a value, stored in the global environment, in the Lua state, accessible to Lua scripts and from the C API.