lua-users home
lua-l archive

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


print(k, v[1],v[2],v[3])

On Tue, Oct 3, 2017 at 9:27 PM, Russell Haley <russ.haley@gmail.com> wrote:
> On Tue, Oct 3, 2017 at 8:39 PM, Sean Conner <sean@conman.org> wrote:
>> 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
>
> Sorry, Seans answer works too. I got confused when the io.write threw an error:
>
> lua_: test.lua:18: bad argument #3 to 'write' (string expected, got table)
> stack traceback:
>     [C]: in function 'io.write'
>     test.lua:18: in main chunk
>     [C]: in ?
>
> This is correct though:
> for k,v in ipairs(data) do
>   --print(k, data[k][1],data[k][2],data[k][3])
>   io.write(k,'-',data[k][1],'-',data[k][2],'-',data[k][3],'\n')
> end
>
> Cheers,
> Russ