它有什么作用?对于i = 1,选择('#',...)

Ale*_*ack 5 lua

我在我正在使用的项目中遇到以下代码.我不明白for循环的迭代部分.什么是select()函数?

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
Run Code Online (Sandbox Code Playgroud)

小智 9

从Lua手册:

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.
Run Code Online (Sandbox Code Playgroud)

Lua内置了多个参数,如果你真的需要,你可以转换成一个表:

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

最后,如果您将"#"作为索引传递,则该函数返回所提供的多个参数的计数:

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)
Run Code Online (Sandbox Code Playgroud)

看到这个网站.