【问题标题】:Lua arguments at wrong memory locationLua 参数在错误的内存位置
【发布时间】:2015-03-16 19:43:42
【问题描述】:

从 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;
}

卢阿:

SetTimer("Durp", 10);

我从该行得到“0x76C44598 处的第一次机会异常:Microsoft C++ 异常:内存位置 0x00D7F588 处的字符”

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

当我调试代码并在弹出异常时按继续时,它会将随机变量抛出到变量中。 double delay 也是如此。

但是当我说:

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

它仍然会给出异常,但会抛出正确的变量。

【问题讨论】:

  • 如果抛出异常,该变量肯定不会包含有效值。
  • 0 永远不是有效的堆栈槽。第一个栈槽是 1。
  • 哦,你是完全正确的,对我这么愚蠢的疏忽。知道为什么 -1 和 -2 也返回正确的值吗?
  • 负索引从栈顶向下计数。
  • 我想知道用LUA_USE_APICHECK 编译lua 是否会发现这个问题。

标签: c++ exception lua lua-api


【解决方案1】:

从我的记忆中,这条线

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

应该是

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多