在Lua中,处理包含nil的varargs的正确方法是什么? [英] In Lua, what is the right way to handle varargs which contains nil?

查看:150
本文介绍了在Lua中,处理包含nil的varargs的正确方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个调试打印功能,该功能将文件句柄作为第一个参数.首先,我编写一个像这样的函数:

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

只要我不在参数中传递nil值,此函数就起作用.但是,如果我用nil调用它,它不会显示nil值和其他参数.

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?

推荐答案

实际上,很容易处理varargs中的nil值,您所需要的就是使用 在Lua 5.2中:

Actually, it's easy to handle nil values in varargs, all you need is to use the select function, which works even with nil (it counts the actual number of parameters). The following idiom is so useful that it is a core library function table.pack in Lua 5.2:

function table.pack(...)
  return { n = select("#", ...), ... }
end

参数的数量存储在字段n中,因此要遍历它们,只需使用以下命令即可:

The number of arguments is stored in field n, so in order to iterate through them just use this:

function vararg(...)
    local args = table.pack(...)
    for i=1,args.n do
        -- do something with args[i], careful, it might be nil!
    end
end

这篇关于在Lua中,处理包含nil的varargs的正确方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆