Question

When calling lua functions from C, it is possible to check how many values were returned by using lua_gettop. This even includes trailing nils - is there a way to do this from only Lua code? This does not work:

function GetValues()
  return 1, 2, 3, nil, nil
end

local t = {GetValues()}
print("Returned "..table.getn(t).." values")

This prints 3. Doing it from C, it is possible to see that 5 values were returned.

Was it helpful?

Solution

In Lua 5.2:

local t = table.pack(GetValues())
print("Returned " .. t.n .. " values")

prints 5.

In Lua 5.1 table.pack is not built-in, but you can define a similar function like this:

function pack(...)
  local t = {...}
  t.n = select('#', ...)
  return t
end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top