tags:

views:

44

answers:

1

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?

+4  A: 

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.

Alexander Rafferty
Thank you. I'm so glad I wasn't losing my mind.
BlueJ774
Well, I just hope I explained it right.
Alexander Rafferty