Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enumerate variable return values with trailing nils

Tags:

lua

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.

like image 859
jakobbotsch Avatar asked Feb 28 '26 12:02

jakobbotsch


1 Answers

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
like image 81
finnw Avatar answered Mar 03 '26 08:03

finnw



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!