Returning a lua table on SWIG call

Posted by Tom J Nowell on Stack Overflow See other posts from Stack Overflow or by Tom J Nowell
Published on 2010-05-01T18:28:05Z Indexed on 2010/05/01 18:38 UTC
Read the original article Hit count: 135

Filed under:
|

I have a class with a methodcalled 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 CSpringGame::GetEnemiesLua(){
 std::vector<springai::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<springai::Unit*>::iterator it = enemies.begin(); it != enemies.end(); ++it) {

   //key
   lua_pushinteger(ai->L,index);//lua_pushstring(L, key);

   //value
   CSpringUnit* unit = new CSpringUnit(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?

© Stack Overflow or respective owner

Related posts about lua

Related posts about swig