1

In brief, I called Lua script function aaa, aaa called C++ function testfunc, and when testfunc going to call script function bbb, it crashed.

This is the Lua-side code:

foo = 100
function aaa()
    testfunc(foo * 2)
end
function bbb(...)
    for val in ... do
        print(val)
    end
end

This is the C++ testfunc, it calls bbb with 3 arguments:

int testfunc( lua_State* lua )
{
    auto arg1 = lua_tointeger( lua, 1 );
    juce::Logger::writeToLog( "testfunc called with argument " + juce::String( arg1 ) );

    int bbb_type = lua_getglobal( lua, "bbb" );
    if ( bbb_type != LUA_TFUNCTION )
    {
        lua_pushstring( lua, "bbb is not function" );
        lua_error( lua );
    }

    lua_pushinteger( lua, 100 );
    lua_pushinteger( lua, 200 );
    lua_pushstring( lua, "deep dark fantasy" );
    lua_call( lua, 3, 0 );

    return 0;
}

In the stack trace of the crash, it seems that in luaD_precall, it does not think the incoming thing is an object, the switch branch went to the last defaultsection that try to find the callable from __call metamethod. However, the type of function object in stack has been checked in testfunc.

Egor Skriptunoff
  • 23,359
  • 2
  • 34
  • 64
jiandingzhe
  • 1,881
  • 15
  • 35
  • 3
    The first argument for `bbb()` must be an iterator (see syntax for generic `for` in Lua manual). In your case Lua is trying to call number `100` because you have passed it instead of iterator. – Egor Skriptunoff Jun 11 '21 at 06:15
  • You're basically doing `for val in 100, 200, "deep dark fantasy" do`. Do you actually want to do `for _, val in ipairs{100, 200, "deep dark fantasy"} do`? – Joseph Sible-Reinstate Monica Jun 12 '21 at 02:45

0 Answers0