Lua参数在错误的内存位置

在从 lua 中解析变量时,lua 的行为很奇怪。

C++:

int LuaManager::SetTimer(lua_State *pLua)
{
    if (!lua_isstring(pLua, 0)) throw "expected: string";
    if (!lua_isnumber(pLua, 1)) throw "expected: number";

    std::string callback = lua_tostring(pLua, 0);
    double delay = lua_tonumber(pLua, 1);
    Timer timer = Timer(callback, delay);

    return 0;
}

lua:

SetTimer("Durp", 10);

我从这行代码中得到了一个“第一次机会异常,位于 0x76C44598:Microsoft C++ 异常:指向内存位置 0x00D7F588 的 char”:

std::string callback = lua_tostring(pLua, 0);

当我调试代码并在异常弹出时按“继续”时,它会将随机变量扔进变量中。对于 double delay 同样如此。

但是,当我说:

std::string callback = lua_tostring(pLua, -2);
double delay = lua_tonumber(pLua, -1);

它仍会抛出异常,但正确的变量会被扔进去。

点赞
用户3772835
用户3772835

从我的记忆中来看,这行代码

std::string callback = lua_tostring(pLua, 0);

应该改为

std::string callback = lua_tostring(pLua, 1);

因为在lua中索引从1开始。

2015-01-19 07:01:38