Search code examples
lua

What does it do? for i=1,select('#',...)


I encountered the following code in a project that I'm working with. i don't understand the iteration part of for-loop. What is the select() function?

function _log (str,...)
  local LOG="/tmp/log.web"
  for i=1,select('#',...) do
    str= str.."\t"..tostring( select(i,...) )
  end
os.execute("echo \"".. str .."\" \>\> " .. LOG )
end

Solution

  • From the Lua manual:

    If index is a number, returns all arguments after argument number index. Otherwise, index must be the string "#", and select returns the total number of extra arguments it received.

    From this post on Lua's multiple arguments and the "select" function, you can convert into a table if you really need to:

    function multiple_args(...)
      local arguments = {...}  -- pack the arguments in a table
      -- do something --
      return unpack(arguments) -- return multiple arguments from a table (unpack)
    end
    

    Finally, if you pass "#" as index, the function returns a count of the multiple arguments provided:

    print(select("#")) --> 0
    print(select("#", {1, 2, 3})) --> 1 (single table as argument)
    print(select("#", 1, 2, 3)) --> 3
    print(select("#", {1,2,3}, 4, 5, {6,7,8}) --> 4 (a table, 2 numbers, another table)