1

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
  • 2
    Not sure what you mean. If you say foo='bar', 'bar' is a value, stored in the global environment, in the Lua state, accessible to Lua scripts and from the C API. Commented Feb 8, 2013 at 17:54

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.