[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: help for newbie -- make an list-table where the key is integer and the value is a hash-table-record
- From: Sean Conner <sean@...>
- Date: Tue, 3 Oct 2017 23:39:24 -0400
It was thus said that the Great douglas mcallaster once stated:
> 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
If I understand what you want, what about?
io,input('d1dat.txt')
io.output('d1dat.out')
data = {}
for l in io.lines() do
a,b,c = string.match(l,"(%w+)|(%d+)|(%w+)")
table.insert(data, { a , b, c })
end
for k,v in ipairs(data) do
io.write(k,'-',data[1],'-',data[2],'-',data[3],'\n')
end
-spc