简体   繁体   中英

lual_newstate outside of main function

I'm embedding Lua in a C++ application using Lua5.1 and I'm having an odd issue with luaL_newstate().

This works:

lua_State *L = NULL;
int main()
{
   L = luaL_newstate();
   return 0;
}

I recently restructured my code and chose to create an init function like this:

lua_State *L = NULL;
void init_lua(lua_State *L)
{
   L = luaL_newstate();
}
int main()
{
   init_lua(L);
   return 0;
}

That doesn't work. For some reason, luaL_newstate() always returns NULL in that situation. But, to add to the confusion, this does work:

lua_State *L = NULL;
void init_lua(lua_State **L)
{
   *L = luaL_newstate();
}
int main()
{
   init_lua(&L);
   return 0;
}

Functionally, I don't see a difference between the second and third examples and yet the second segfaults as soon as I attempt a lua call using L and the third works just fine. What is happening here?

In the second example, this function:

void init_lua(lua_State *L)
{
  L = luaL_newstate();
}

You are setting L to the return of luaL_newstate(). L is a pointer to a lua_state. However, you are only changing the parameter version of L.

In you third example:

void init_lua(lua_State **L)
{
  *L = luaL_nwstate();
}

You are setting the value pointed to by L (which is your globally defined L) to the return of luaL_newstate(). So you are changing the actual variable passed to the function.

In summary: when you pass a VALUE in the second example, the function cannot change the original variable. But when you pass a POINTER to your variable in your third, the function can change the value of that variable using the address you passed to it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM