tags:

views:

131

answers:

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?

+2  A: 

When you use the colon in function AI:UnitCreated(unit), it creates a hidden self parameter that receives the AI instance. It actually behaves like this:

function AI.UnitCreated(self, unit)

So when calling that function from C, you need to pass both parameters: the ai instance and the unit parameter. Since you passed only one parameter, self was set to it and unit was set to nil.

interjay
ah so calling getglobal("ai") and then pushing my swig pointer and doing 2 parameters should fix it? ^_^
Tom J Nowell
@Tom: Yes, that should fix it.
interjay
worked like a chalm =]
Tom J Nowell