lua-users home
lua-l archive

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


Would a kind soul please help me get started with a simple job task.

Below job runs but returns the last record from my data file for all six lines in the data file.
The print statements echo that it is working as I expect up until the table.insert command

I have looked thru both PiL and Beginning Lua Programming and cannot find how to properly do this simple task.

+++++++++++++++++++++++++++++

-- lines from input file d1dat.txt:
-- one|123|aaa
-- one|123|a
-- two|45|a
-- three|6789|b
-- on1|123|b
-- tw1|45|c
-- th1|6789|c

io.input  ('d1dat.txt')
io.output ('d1dat.out')
    l= '_' -- scalar -- a line (char) from input file
 rows= {}  -- a list ie int,val_l -- use ipairs
 cols= {}  -- a hash ie nam,val   -- use  pairs
 dsn1= {}  -- a list ie int,tbl   -- use ipairs

for l in io.lines()
 do rows[#rows+1]= l
 end

for _,v in ipairs(rows)
 do local   a    = '_'
    local     b  =  0
    local       c= '_'
            a,b,c= string.match (v, "(%w+)|(%d+)|(%w+)") -- parse the line
    print (a,b,c)
    cols['v1']= a -- populate the hash (table)
    cols['v2']= b
    cols['v3']= c
    for kc,vc in pairs (cols) do print(kc,vc) end
    table.insert (dsn1, cols) 
--  dsn1 [ #dsn1+1 ]=   cols -- gives same result: every row in dsn1 is the last row from input file
 end

for k,v in ipairs (dsn1)
 do io.write (k ,'-' ,v.v1 ,'-' ,v.v2 ,'-' ,v.v3 ,'\n')
 end
-- d1dat.out:
-- 1-th1-6789-c
-- 2-th1-6789-c
-- 3-th1-6789-c
-- 4-th1-6789-c
-- 5-th1-6789-c
-- 6-th1-6789-c