Is the lua_State pointer passed to lua_CFunctions guaranteed to point to the same state as was used to invoke the function?

StackOverflow https://stackoverflow.com/questions/17600753

  •  02-06-2022
  •  | 
  •  

Question

Context: I am working on a set of bindings, and many of my functions reference the "global" Lua state. (It's not actually global in the code I am developing, but local to the particular runtime instance, so global in that all of the callback functions have access to shared state.)

The Lua documentation does not seem to specify whether the pointer passed to a lua_CFunction is guaranteed to be a pointer to the exact same lua_State object as was used to invoke the function (directly via lua_cpcall() or indirectly by invoking Lua code that invokes the C function).

A small test shows that the pointers reference the same object, but I do not know if this is guaranteed.

#include <stdio.h>
#include <lua5.1/lua.h>
#include <lua5.1/lauxlib.h>

static lua_State *state;

static int test_fn(lua_State *L)
{
    printf("global:%p local:%p\n", state, L);
    return 0;
}

int main(int argc, char const **argv)
{
    state = luaL_newstate();

    luaL_openlibs(state);
    lua_register(state, "test_fn", test_fn);

    luaL_dostring(state, "test_fn()");

    lua_close(state);
}

Example output:

global:0x87ef008 local:0x87ef008

I know that Lua gives the function a stack that contains only the arguments to that function, and that makes me a bit uneasy that perhaps this could be implemented by passing that function a different state pointer that is tracking an independent stack. It could also be implemented any number of other ways that would not require a different lua_State -- and in fact I expect that it does work this way -- but the documentation doesn't seem to explicitly say either way.

Are these pointers guaranteed to be equal? If not, under what circumstances might they differ?

Was it helpful?

Solution

If your C function is called from Lua code, then the lua_State argument will be the Lua thread of the calling Lua function.

If your Lua code does not use coroutines, there is only one thread, so you will always get the global state.

OTHER TIPS

Doug's answer is correct, but to further elaborate, the state pointer is -not- guaranteed to be the same, and will most likely be different, when you use coroutines.

For an example of this going wrong, see the problem I was just in a few hours ago.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top