开发者

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


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)
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜