在Lua中,处理包含nil的可变参数的正确方法是什么?
我正在尝试创建一个调试打印函数,它将文件句柄作为第一个参数。首先,我编写一个如下所示的函数:
function fprint (f, ...)
for i, v in ipairs{...} do
f:write(tostring(v))
f:write("\t")
end
f:write("\n")
end
只要我不在参数中传递 nil
值,该函数就可以工作。但是,如果我用 nil
调用它,它不会打印 nil
值和其余参数。
fprint(io.stderr, 1, 2, nil, 3)
=> prints only 1 and 2
那么,解决这个问题的正确方法是什么?
I'm trying to create a debug print function which takes a file handle as the first argument. First, I write a function like this:
function fprint (f, ...)
for i, v in ipairs{...} do
f:write(tostring(v))
f:write("\t")
end
f:write("\n")
end
This function works as long as I don't pass nil
value in arguments. But if I call this with a nil
, it doesn't print the nil
value and rest of arguments.
fprint(io.stderr, 1, 2, nil, 3)
=> prints only 1 and 2
So, what is the right way to fix this problem?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
实际上,处理 varargs 中的
nil
值很容易,您所需要做的就是使用select
函数,即使使用nil
也能工作(它计算参数的实际数量)。下面的习惯用法非常有用,它是一个核心库函数table.pack
:参数的数量存储在字段
n
中,因此为了迭代它们,只需使用:Actually, it's easy to handle
nil
values in varargs, all you need is to use theselect
function, which works even withnil
(it counts the actual number of parameters). The following idiom is so useful that it is a core library functiontable.pack
in Lua 5.2:The number of arguments is stored in field
n
, so in order to iterate through them just use this:据我所知,没有简单的独立于实现的方法来知道包含
nil
条目的数组的长度,因为#
操作可以指向后面跟着一个的任何位置nil
,但这是一个依赖于实现的快速解决方案,它将打印nil
。您可能会变得复杂(因此与实现无关),而不是依赖于
#
,因为您知道parm
表是一个数组并使用如下内容:如果您可以跳过
nil
值和顺序并不重要,那么切换到pairs
会容易得多。As best I know, there's no easy implementation independent way to know the length of an array that contains
nil
entries since the#
operation can point to any position that is followed by anil
, but this is a quick implementation dependent solution that will print thenil
.Rather than relaying on
#
, you can get complicated (and therefore implementation independent) since you know theparm
table is an array and use something like this:If you can skip the
nil
values and order isn't important, then switching topairs
would be much easier.