lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


Alexander Gladysh wrote:
I think you want to test for empty string, that is not the same as nil.
Try this one:

for count = 1, math.huge do
   local line = io.read()
   if #line == 0 then break end
   io.write(string.format("%6d ", count), line, "\n")
end

A little note: this is kind of slower way to check if string is empty.
Fastest would be to compare with empty string constant:

for count = 1, math.huge do
   local line = io.read()
   if line == "" then break end
   io.write(string.format("%6d ", count), line, "\n")
end

Please note that the difference is quite small though (note 10^9 iterations).

Instead of such small differences, why not add an empty function call and then subtract out the function call overhead and loop overhead. Then we can compare the different comparisons in nanoseconds.

Benchmarking results follow.

Legend: "empty" is test with line being empty string, "nonempty" --
with non-empty string. The "constant" is `line == ""`, "size" is
`#line == 0` and "upvalue" is comparison with upvalue, containing
empty string.
[snip snip]

--
Cheers,
Kein-Hong Man (esq.)
Kuala Lumpur, Malaysia