lua-users home
lua-l archive

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


Title: Lua 5 iterator question
It's more like this
 
----------- CUT HERE -----------------------------
function lineIterator(str)
   local pos
   local function lineIterate()
           if not pos then
              pos = 0
           end
           local s1 = string.find(str, "\n", pos, true)
           local line
           if not s1 then
              pos = nil
           else
              line = string.sub(str, pos, s1-1)
              pos = s1 + 1
           end
           return line
   end
   return lineIterate  
end
 
s = [[
***hello
***this
***is
***a
***string
]]

s1 = [[
   ###
   @@@
]]
 
for line in lineIterator(s) do
   print(line)
   for line2 in lineIterator(s1) do
       print(line2)
   end
end
----------- CUT HERE -----------------------------
 
I am sure this could be more optimal as the iterator creates new function on every iteration.
Alex
-----Original Message-----
From: Stewart, Joseph [mailto:Joseph.Stewart@sciatl.com]
Sent: Thursday, February 12, 2004 7:06 AM
To: 'Lua list'
Subject: Lua 5 iterator question

Hello all,

I've read the lua 5 documentation and looked at the iterator tutorial, but I'm still stumped on how to create an interator function that will step through a string a line at a time.

Here's the code I've come up with so far (from memory, the code is a home):

function lineIterate(state,n)
        local s1
        s1 = string.find(n, "\n", state)
        if not s1 then return nil end
        return s1+1, string.sub(n, state, s1)
end

s = [[hello
this
is
a
string]]

for i,v in lineIterate(i, s) do print(v) end

Am I way off base? Thanks for all suggestions!
-joe



- - - - - - - Appended by Scientific-Atlanta, Inc. - - - - - - -
This e-mail and any attachments may contain information which is confidential, proprietary, privileged or otherwise protected by law. The information is solely intended for the named addressee (or a person responsible for delivering it to the addressee). If you are not the intended recipient of this message, you are not authorized to read, print, retain, copy or disseminate this message or any part of it. If you have received this e-mail in error, please notify the sender immediately by return e-mail and delete it from your computer.