Reputation: 6220
I am a newbie to Lua so kindly bear with me. I have 2 csv strings in Lua
a= '1,2,3,4,5'
represents the index and
b='this,needs,to,be,matched:with,every,single,row,here:'
The rows are separated by a ':' character instead of newline
Expected output
1,this,2,needs,3,to,4,be,5,matched
1,with,2,every,3,single,4,row,5,here
I tried iterating through the them separately with the following code
local result= {}
local u = unpack or table.unpack
for values in string.gmatch(values_csv, '([^:]+)') do
local data = {}
for column1,column2 in string.gmatch(values, '([^,]+)'),string.gmatch(keys, '([^,]+)') do
print(column1, column2)
end
end
For some reason the second one is always nil. I cant find a zip function similar to Python in Lua without external libs. How do I iterate both simulatenously. Thanks for the help
Upvotes: 1
Views: 90
Reputation: 3225
A variation of Egor's solution to get the output as you asked:
a = '1,2,3,4,5'
b = 'this,needs,to,be,matched:with,every,single,row,here:'
for line in b:gmatch '[^:]+' do
local idx = a:gmatch '%d+'
local ans = {}
for v in line:gmatch '[^,]+' do
ans[#ans+1] = idx()
ans[#ans+1] = v
end
print(table.concat(ans,','))
end
Upvotes: 2
Reputation: 974
local keys = '1,2,3,4,5'
local values_csv = 'this,needs,to,be,matched:with,every,single,row,here:some,values,,are,absent:'
for values in values_csv:gmatch'[^:]+' do
local data = {}
local keys_iter = keys:gmatch'[^,]+'
for value_column in (values..','):gmatch'([^,]*),' do
print(keys_iter(), value_column)
end
end
Upvotes: 1