lua-users home
lua-l archive

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

On Tue, Oct 3, 2017 at 8:59 PM douglas mcallaster <> wrote:
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

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

for k,v in ipairs (dsn1)
 do io.write (k ,'-' ,v.v1 ,'-' ,v.v2 ,'-' ,v.v3 ,'\n')
-- 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

Tables are mutable, so in the "ipairs(rows)" loop, you're just modifying the same table over and over and storing another reference to it in "dsn1". Each of those references points to the same table and thus you get whatever values were stored in that table last.

You need to create a new table each time through the loop. Try taking the "cols = {}" line and moving it into the "ipairs(rows)" loop (and ideally prefix that line with "local" so that "cols" doesn't hang around afterward). This will ensure that a new table is created on each iteration, so that "dsn1" contains references to different tables.