如何使用Luacneneneba API正确读取字符串和表参数

How to properly read string and table arguments with Lua c API?

本文关键字:字符串 参数 读取 何使用 Luacneneneba API      更新时间:2023-10-16

我花了几个小时试图让它发挥作用,但没有成功。我有一个C++程序,它的功能暴露在Lua脚本中。Lua脚本这样使用它:

setData('type', {a=1, b=2, c=3})

所以第一个参数是字符串,第二个是表。

我当前最好的C++setData函数版本如下:

string sType;
map<string, uint8_t> mOptions;
int nArgs = lua_gettop(i_pState);
if (nArgs == 2)
{
if (lua_isstring(i_pState, 1) != 0)
sType = lua_tostring(i_pState, 1);
if (lua_istable(i_pState, 2) != 0)
{
lua_pushnil(i_pState);
while(lua_next(i_pState, 2))
{
uint8_t nValue = uint8_t(lua_tonumber(i_pState, -1));
string  sKey   = lua_tostring(i_pState, -2);
mOptions[sKey] = nValue;
lua_pop(i_pState, 1);
}
lua_pop(i_pState, 1);
}
}
return 0;

它工作正常,但在调用lua_close()函数时,会在结束时导致"program.exe已触发断点"错误。这个代码出了什么问题?

UPD1。如果不处理第二个参数,我不会出错。

UPD2.我的代码行为非常奇怪。我认为这可能是混合extern "C"和C++代码的问题。

UPD3。原来这是堆损坏。我不明白原因在哪里。也许这与lua根本没有关系。

终于来了!将Lua代码重新编译为C++代码不起作用(积极的一面是我再也不用担心extern "C"了(。但我发现了两个多余的lua_pop()呼叫。我去掉了它们,现在效果很好。

我没想到卢会这么危险