开发者

How to get multiple return values when calling c++ from lua scripts?

//c++ funciton definition
int LS_SomeFucntion(LuaState* state)
{
LuaStack args(state);
//.. 
set<int>::iterator it = mySet.begin();
for(; it != mySet.end(); ++it)
{
    state.pushInteger(*it);
}
return mySet.size();

}

state->GetGlobals().Register(开发者_如何学运维"SomeFunction",LS_SomeFunction);

//lua scripts
??? = SomeFunction()

How to get the return value of SomeFunction() in lua scripts when the size is not know when the function is called?


You can capture all the return values in a table:

local rv = { SomeFunction() }

print('SomeFunction returned', #rv, 'values')
for i,val in ipairs(rv) do
    print(i,val)

Or process them using a variable parameter list:

function DoSomething(...)
   local nargs = select('#', ...)
   print('Received', nargs, 'arguments')
   for i=1,nargs do
      print(i,select(i,...))
end

DoSomething(SomeFunction())

Of course, your C function should probably just return a Lua table containing the list items. I'm not familiar with the LuaPlus, but judging from the documentation here, you'd want something like this:

int LS_SomeFunction(LuaState* state)
{
   LuaObject table;
   table.AssignNewTable(state, mySet.size()); // presize the array portion

   int i = 1;
   for(set<int>::iterator it = mySet.begin(); it != mySet.end(); ++it)
       table.SetNumber(i++, *it);

   table.PushStack();
   return 1;
}

Then you just say:

local rv = SomeFunction()
print('SomeFunction returned', #rv, 'values')
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜