How to correctly redefine print in Lua 5.3?

914 views Asked by At

I frequently use print function for debugging in conjunction with os.exit(). I don't want to type os.exit() each time I use print, so I want to redefine this function.

> function pprint(...)
>> for _,a in ipairs(arg) do
>> print(a)
>> end
>> os.exit()
>> end


> pprint('hello',1,2,3)
hello
1
2
3
[johndoe@dell-john ~]$ 

Although this works in Lua 5.1, it does not work in Lua 5.3 and, for some reason, Torch. I looked up the Lua 5.3 docs for "triple dots" expression but couldn't find the reference on how to access ... arguments. Can you explain what was changed and how to redefine print for Lua 5.3?

2

There are 2 answers

0
lhf On BEST ANSWER

Automatic creation of the arg table for vararg functions was deprecated in Lua 5.1 and removed in Lua 5.2.

As mentioned by Egor, use

for _,a in ipairs({...}) do

instead of

for _,a in ipairs(arg) do

Or add

local arg={...}

at the start of the function.

0
Xt Z On

for _,a in ipairs({...}) do is wrong ,it does not support nil

right rewrite

local arg = table.pack(...)
for i = 1 ,arg.n do
    old_print(arg[i])
end