1

I'm using SWIG to wrap C++ objects for use in lua, and Im trying to pass data to a method in my lua script, but it always comes out as 'nil'

void CTestAI::UnitCreated(IUnit* unit){
    lua_getglobal(L, "ai");
    lua_getfield(L, -1, "UnitCreated");
    swig_module_info *module = SWIG_GetModule( L );
    swig_type_info *type = SWIG_TypeQueryModule( module, module, "IUnit *" );
    SWIG_NewPointerObj(L,unit,type,0);
    lua_epcall(L, 1, 0);
}

Here is the lua code:

function AI:UnitCreated(unit)
   if(unit == nil) then
      game:SendToConsole("I CAN HAS nil ?")
   else
      game:SendToConsole("I CAN HAS UNITS!!!?")
   end
end

unit is always nil. I have checked and in the C++ code, the unit pointer is never invalid/null

I've also tried:

void CTestAI::UnitCreated(IUnit* unit){
    lua_getglobal(L, "ai");
    lua_getfield(L, -1, "UnitCreated");
    SWIG_NewPointerObj(L,unit,SWIGTYPE_p_IUnit,0);
    lua_epcall(L, 1, 0);
}

with identical results.

Why is this failing? How do I fix it?

4

1 回答 1

2

当您在 中使用冒号时,它会创建一个接收实例function AI:UnitCreated(unit)的隐藏参数。它实际上的行为是这样的:selfAI

function AI.UnitCreated(self, unit)

因此,当从 C 调用该函数时,您需要传递两个参数:ai实例和unit参数。由于您只传递了一个参数,self因此设置为它并unit设置为nil.

于 2010-03-09T20:21:15.107 回答