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?
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 .
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.
Lua denotes the string concatenation operator by " .. " (two dots).
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With