I have this code:
int foo(lua_State *L)
{
lua_checkstack(L, 10);
lua_pushvalue(L, 1);
lua_pushnil(L);
lua_next(L, -2);
return 0;
}
void bar()
{
lua_State* L = luaL_newstate();
lua_pushcfunction(L, foo);
lua_setglobal(L, "foo");
luaL_dostring(L, "foo()");
}
When I call bar(), it crashes within a call to lua_next, within the code generated for line
more = luaH_next(L, hvalue(t), L->top - 1);
in lapi.c.
There is no crash when I modify the last line in bar() to read luaL_dostring(L, "foo()").
This happens with Lua 5.3.3.
As far as I can tell, the call to lua_checkstack() ensures that the stack size is at least ten more on top of the current position before lua_pushvalue() is called, which, according to section 4.3, makes index 1 an acceptable index even when foo() is called without arguments. lua_pushvalue is not "noted otherwise", so it must work with the acceptable index 1, then, per 4.3 again: "For functions that can be called with acceptable indices, any non-valid index is treated as if it contains a value of a virtual type LUA_TNONE, which behaves like a nil value."
So lua_pushvalue() must push something that "behaves like a nil value". After the call to lua_pushnil(), stack index -2 must be s a valid stack index. Yet lua_next() crashes.
When, on the other hand, a true nil is passed, there is no crash.
What am I missing?
Cheers,
V.