lua_gettop 返回 0 但是栈并不表现得空

当我运行下面的代码片段时:

pState = luaL_newstate();
if( !pState )
    return false;

luaL_requiref( pState, "_G", luaopen_base, 1 );
luaL_requiref( pState, "table", luaopen_table, 1 );
luaL_requiref( pState, "string", luaopen_string, 1 );
luaL_requiref( pState, "math", luaopen_math, 1 );
luaL_requiref( pState, "debug", luaopen_debug, 1 );
luaL_requiref( pState, "package", luaopen_package, 1 );
lua_pop( pState, 6 );
// 清空栈
lua_settop( pState, 0 );

//...

lua_newtable( pState );
lib_indx = lua_gettop( pState );
CLuaManager::PrintStack( pState );

lib_indx 的值为0,而且我的 PrintStack 函数(与文档中呈现的相同)显示栈为空。但是,如果我尝试执行任何使用栈顶值的操作,它们都像表在栈顶一样工作。例如,以下代码:

lua_newtable( pState );
lib_indx = lua_gettop( pState );
lua_setglobal( pState, "TestTable" );

结果不会产生错误,表 "TestTable" 可以通过脚本访问:

function dump(o)
   if type(o) == 'table' then
      local s = '{ '
      for k,v in pairs(o) do
         if type(k) ~= 'number' then k = '"'..k..'"' end
         s = s .. '['..k..'] = ' .. dump(v) .. ','
      end
      return s .. '} '
   else
      return tostring(o)
   end
end

print("TestTable:", dump(TestTable))

注释掉 lua_setglobal( pState, "TestTable" ); 这一行将导致输出 TestTable: nil,而取消注释则导致 TestTable: { }。这表明该表被设置为全局值 TestTable。然而,lib_indx 仍然为零!那么Lua在哪里找到了这个表?

点赞
用户953613
用户953613

我发现了这种行为的原因。一个错放的 lua_pop 显然会导致栈大小为负数,因此新的表格是被添加到栈中但是在意料之外的索引位置。

2019-01-30 00:26:35