C++ 为什么Lua在这段代码中返回一个空表?
编辑: 正如我之前所评论的,我的问题是我不能在C中创建一个使用字符串作为键的表。我制作了一个快速测试程序,演示了我遇到的问题:C++ 为什么Lua在这段代码中返回一个空表?,c++,lua,C++,Lua,编辑: 正如我之前所评论的,我的问题是我不能在C中创建一个使用字符串作为键的表。我制作了一个快速测试程序,演示了我遇到的问题: 这里是C++的一部分: #include <lua.hpp> #include <String.h> BString LuaTypeToString(lua_State *L, int index, int type) { BString out; switch (type) { case LUA_TST
这里是C++的一部分:
#include <lua.hpp>
#include <String.h>
BString
LuaTypeToString(lua_State *L, int index, int type)
{
BString out;
switch (type)
{
case LUA_TSTRING:
{
out << "'" << lua_tostring(L, index) << "'";
break;
}
case LUA_TBOOLEAN:
{
out << (lua_toboolean(L, index) ? "true" : "false");
break;
}
case LUA_TNUMBER:
{
out << (float)lua_tonumber(L, index);
break;
}
default:
{
out << lua_typename(L, type);
break;
}
}
return out;
}
void
DumpLuaTable(lua_State *L, int tableIndex)
{
lua_pushnil(L);
printf("\t{ ");
while (lua_next(L, tableIndex) != 0)
{
BString keyString = lua_tostring(L, -2);
BString valueString;
int type = lua_type(L, -1);
if (type == LUA_TTABLE)
DumpLuaTable(L, lua_gettop(L));
else
valueString = LuaTypeToString(L, -1, type);
printf("%s=%s,",
keyString.String(),
valueString.String());
lua_pop(L, 1);
if (lua_isnumber(L, -1))
{
lua_pop(L, 1);
break;
}
}
printf(" }");
}
void
DumpLuaStack(lua_State *L)
{
printf("DumpLuaStack:\n");
int top = lua_gettop(L);
for (int i = 1; i <= top; i++)
{
int type = lua_type(L, i);
if (type == LUA_TTABLE)
DumpLuaTable(L, i);
else
printf("\t%s ", LuaTypeToString(L, i, type).String());
}
printf("\n");
}
static
int
ReturnTable(lua_State *L)
{
lua_newtable(L);
lua_pushnumber(L, 3.14);
lua_pushstring(L, "1");
lua_settable(L, -3);
DumpLuaStack(L);
return 1;
}
int
main(void)
{
lua_State *L = luaL_newstate();
luaL_openlibs(L);
lua_pushcfunction(L, ReturnTable);
lua_setglobal(L, "ReturnTable");
int status = luaL_dofile(L, "luatest.lua");
if (status)
printf("Status = %d: %s\n", status, lua_tostring(L, -1));
lua_close(L);
return status;
}
function DumpTable(table)
print("LuaDumpTable")
local out = "\t"
if #table > 0 then
for i, v in ipairs(table) do
out = out .. i .. "=" .. v .. " "
end
print(out)
else
print("\tEmpty table")
end
end
value = ReturnTable()
if (type(value) == "table") then
DumpTable(value)
else
print(type(value))
end
代码按原样工作没有问题——Lua脚本打印出您所期望的内容。将推动3.14到堆栈的行更改为,例如,
lua_pushstring(L,“foo”)代码>我得到的只是Lua一侧的一张空桌子。你知道我做错了什么吗?你在Lua中错误地检查了表格:
如果#表>0,则
#表
只是告诉您表中第一个未使用的整数是0。将字符串插入到表中时,它不会增加计数,因为它不是连续数组的一部分,也不能使用ipairs
处理它。只要切换到使用配对
,您就会看到foo
:
函数转储表(表)
打印(“LuaDumpTable”)
本地输出=“\t”
对于i,v成对(表)do
出局。。我"=" .. v" "
结束
打印(输出)
结束
旧注释,留作参考:
我怀疑这会导致问题,但对于从Lua调用API,您通常希望从堆栈中弹出输入。因此,在lua_tonumber
呼叫之后:
int32值=lua\u tonumber(L,1);
卢厄波普(L,1);
rgb_color c=ui_color((color_哪个)值);
我唯一能想到的就是显示用于确定表为空的Lua代码。你在这里展示的一切似乎都是正确的。你读过B米奇的评论吗?你看到他在DumpTable版本中没有使用#table
了吗?你看到他是如何不使用ipairs
而使用pairs
的了吗?为什么不这样做,看看它是如何工作的。在等待答案的时候,我把我正在做的事情简化为一个快速测试项目。返回使用字符串作为键的表时遇到问题。我马上就要出门了,但我回来后会把修订本贴出来的。当然要拍额头!我忘记了#运算符(和lua_objlen)只计算整数索引。我不知道ipairs vs pairs的事,所以非常感谢你们两位的时间和耐心