lua_next segfault on LUA_ENVIRONINDEX?

Viewed 76

The following C program that uses the Lua API lua_next function to try and begin iterating LUA_ENVIRONINDEX table crashes in call to lua_next...

#include <lua5.1/lua.hpp>

int main() {
  lua_State* L = luaL_newstate();
  lua_pushnil(L);
  lua_next(L, LUA_ENVIRONINDEX);
}

Any idea why?

1 Answers

The manual says that LUA_ENVIRONINDEX "gives the environment of the running C function". In your code, there is no "running C function" in the sense of Lua: main was not called from Lua.

Take lua.c. If you put your code in main, then there is a crash, as you have found out. If you put your code in pmain, which is called from Lua, then there is no crash.

Related