【问题标题】:Lua unprotected error using lua_pcall使用 lua_pcall 的 Lua 不受保护的错误
【发布时间】:2013-08-12 00:58:20
【问题描述】:

我正在使用受 Lua 保护的调用,但我收到了一个不受保护的错误:

lua_getfield( m_L, LUA_GLOBALSINDEX, "startIteration" );    // 1
if( lua_isfunction( m_L, -1 ) ){
    lua_pushnumber( m_L, n );                               // 2
    auto ret = lua_pcall( m_L, 1, 0, 0 );                   // 0
    checkLuaReturn( m_L, ret );
}else{
    lua_pop( m_L, 1 );                                      // 0
}

错误是:

PANIC: unprotected error in call to Lua API (../example/ex01.lua:31: attempt to index global 'raster' (a nil value))

Lua 代码是:

function startIteration( num )
   io.write( "Start iteration " .. num .. "\n" )
   raster.grass.save( "output.png" )
end

我怎样才能解决它,以获得真正受保护的呼叫?

更新:修复了额外的弹出窗口

【问题讨论】:

  • 你确定这是实际执行 Lua 脚本的代码吗?至少对lua_pcall 的调用似乎很好,所以问题可能隐藏在其他地方。但是,if 分支中的第一个lua_pop 存在问题。您将 0 作为第三个参数传递给 lua_pcall,因此 pop 仅在发生错误时才有效。请记住,pcall 从堆栈中消耗函数及其参数。
  • 我确定这是脚本的地方,我在其他地方不使用“startIteration”。
  • 另外,lua_pop 是将 lua_getfield 压入堆栈的值去掉。错误值在 checkLuaReturn 函数中被移除。
  • 但这就是重点:lua_pcall already removed 来自lua_getfield 的值。所以在lua_pop 之后,您的堆栈位于-1 而不是0
  • 你是正确的@ComicSansMS,它删除了额外的流行音乐,但错误仍然存​​在

标签: lua


【解决方案1】:

这似乎与您的 lua_pcall() 无关,而是与您的 lua 代码有关。 raster.grass.save( "output.png" ) 行是错误所在。

尝试将其更改为以下内容:

if raster and type(raster) == 'table' then
    if raster.grass and type(raster.grass) then
        raster.grass.save()
    end
end

但是,这并不能解决您的问题,问题是您在创建 raster 之前调用了变量 raster 的成员。

【讨论】:

  • 问题是为什么 Lua 会因为调用受到保护而恐慌。
  • 正如@lhf 所说,问题在于lua 恐慌,而不是lua 代码中存在错误。还是谢谢
猜你喜欢
  • 2014-12-30
  • 1970-01-01
  • 2012-08-14
  • 2013-07-05
  • 1970-01-01
  • 1970-01-01
  • 2014-11-13
  • 1970-01-01
  • 2011-12-26
相关资源
最近更新 更多