它是干什么用的?for i=1,select('#',...)

我在一个项目中遇到了以下代码。我不理解 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

原文链接 https://stackoverflow.com/questions/6929117

点赞
stackoverflow用户1366033
stackoverflow用户1366033

Lua手册

如果 index 是一个数字,则返回参数编号在 index 后面的所有参数。否则,index 必须是字符串 "#"select 函数返回它接收到的额外参数总数。

从这篇Lua多个参数和“select”函数的文章中,如果确实需要,可以将其转换为表格:

function multiple_args(...)
  local arguments = {...}  -- 在表中打包参数
  -- 做一些事情 --
  return unpack(arguments) -- 从表中返回多个参数(解包)
end

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

print(select("#")) --> 0
print(select("#", {1, 2, 3})) --> 1 (作为单个表的参数)
print(select("#", 1, 2, 3)) --> 3
print(select("#", {1,2,3}, 4, 5, {6,7,8}) --> 4 (一个表,2个数字,另一个表)
2011-08-03 15:35:47