In Lua, how to get all arguments, including nil for a variable number of arguments?

For a variable number of arguments, here is an example from lua.org :

function print (...) for i,v in ipairs(arg) do printResult = printResult .. tostring(v) .. "\t" end printResult = printResult .. "\n" end 

From the code example above, if I call

print ("A", "B", nil, nil, "D")

only "A" and "B" are passed, all arguments, since the first nil is ignored. Thus, the print result is “AB” in this example.

Is it possible to get all arguments, including nils? For example, I can check if the argument is nil, and if so, I can print "nil" as a string. So in this example, I really want to print

 AB nil nil D 

after some code modification, of course. But my question is ... first of all, how to get all the arguments, even if some of them are Nile?

+6
source share
1 answer

You tried:

 function table.pack(...) return { n = select("#", ...); ... } end function show(...) local string = "" local args = table.pack(...) for i = 1, args.n do string = string .. tostring(args[i]) .. "\t" end return string .. "\n" end 

Now you can use it as follows:

 print(show("A", "B", nil, nil, "D")) 

Hope this helps.

+7
source

All Articles