I have a class with a method called GetEnemiesLua. I have bound this class to lua using SWIG, and I can call this method using my lua code.
I am trying to get the method to return a lua table of objects.
Here is my current code:
void CGame::GetEnemiesLua(){
std::vector<Unit*> enemies = callback->GetEnemyUnits();
if( enemies.empty()){
lua_pushnil(ai->L);
return;
} else{
lua_newtable(ai->L);
int top = lua_gettop(ai->L);
int index = 1;
for (std::vector<Unit*>::iterator it = enemies.begin(); it != enemies.end(); ++it) {
//key
lua_pushinteger(ai->L,index);//lua_pushstring(L, key);
//value
CUnit* unit = new CUnit(callback,*it,this);
ai->PushIUnit(unit);
lua_settable(ai->L, -3);
++index;
}
::lua_pushvalue(ai->L,-1);
}
}
PushIUnit is as follows:
void CTestAI::PushIUnit(IUnit* unit){
SWIG_NewPointerObj(L,unit,SWIGTYPE_p_IUnit,1);
}
To test this I have the following code:
t = game:GetEnemiesLua()
if t == nil then
game:SendToConsole("t is nil! ")
end
The result is always 't is nil', despite this being incorrect. I have put breakpoints in the code and it is indeed going over the loop, rather than doing lua_pushnil
.
So how do I make my method return a table when called via lua?