Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Lua, what is the right way to handle varargs which contains nil?

Tags:

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?

like image 533
torus Avatar asked Aug 25 '11 00:08

torus


People also ask

What does 3 dots mean in Lua?

The three dots ( ... ) in the parameter list indicate that the function has a variable number of arguments. When this function is called, all its arguments are collected in a single table, which the function accesses as a hidden parameter named arg .

How do you use args in Lua?

To pass arguments into Lua, the script name and arguments must be enclosed within double quotes. The arguments are stored within the arg variable in Lua, which is a table of strings.

What is Dot Dot Lua?

Lua denotes the string concatenation operator by " .. " (two dots).

What is parameter in Lua?

The parameter passing mechanism in Lua is positional: When we call a function, arguments match parameters by their positions. The first argument gives the value to the first parameter, and so on. Sometimes, however, it is useful to specify the arguments by name.


1 Answers

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 

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 
like image 81
Michal Kottman Avatar answered Sep 29 '22 14:09

Michal Kottman