lua-users home
lua-l archive

RE: Lua 5 iterator question

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



The simplest way to iterate through a string a line at a time (if you don't care about blank lines):

for line in string.gfind(str, "[^\n]+") do print(string.format("%q", line)) end

This will skip empty lines, but not lines with only whitespace.

There are variations on the theme. For example, the following will trim whitespace from
both ends of each line, and just return non-blank lines:

for line in string.gfind(str, "%s*([^\n]*%S)%s*\n?") do
print(string.format("%q", line))
end

I suppose that doesn't help you learn how to write iterators, though :)

Here is a simple iterator which returns a vector in pairs:

function two_at_a_time(v)
local i = 1
local function helper(v)
local a, b
a, b, i = v[i], v[i + 1], i + 2
if a and b then return a, b end
end
return helper, v
end

Note that we cannot use the iterator variable here because we don't want
it to pop out during the for loop, the expected pattern would be:

for first, second in two_at_a_time(vec) do
print(first * second)
end

But if we actually wanted the index, we could write the iterator
more simply, and more efficiently:

do
local function helper(v, i)
local i, a, b = i + 2, v[i], v[i + 1]
if a and b then return i, a, b end
end

function two_at_a_time(v) return helper, v, 1

AltStyle によって変換されたページ (->オリジナル) /