0
//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?

1
  • It appears you're not using the standard C API for Lua. What C++ binding are you using? Commented Nov 9, 2010 at 5:21

1 Answer 1

4

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')
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.