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

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

问题描述

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

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("	")
   end
   f:write("
")
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 值很容易,您只需要使用 select 函数,即使与 nil(它计算参数的实际数量).下面这个成语非常有用,它是一个核心库函数table.pack:

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 的可变参数的正确方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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