【问题标题】:How do I achieve this loop in Lua without external libraries如何在没有外部库的情况下在 Lua 中实现这个循环
【发布时间】:2018-05-22 07:38:42
【问题描述】:

我是 Lua 的新手,所以请多多包涵。我在 Lua 中有 2 个 csv 字符串

a= '1,2,3,4,5'

表示索引 和

b='this,needs,to,be,matched:with,every,single,row,here:'

行由':'字符而不是换行符分隔

预期输出

1,this,2,needs,3,to,4,be,5,matched
1,with,2,every,3,single,4,row,5,here

我尝试使用以下代码分别迭代它们

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

由于某种原因,第二个总是为零。如果没有外部库,我在 Lua 中找不到类似于 Python 的 zip 函数。我如何同时迭代两者。感谢您的帮助

【问题讨论】:

    标签: lua iterator lua-table


    【解决方案1】:

    Egor 解决方案的一种变体,可按照您的要求获取输出:

    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
    

    【讨论】:

      【解决方案2】:
      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
      

      【讨论】:

      • 点赞!谢谢,它给了我一个错误stdin:1:尝试索引一个零值(全局'values_csv')堆栈回溯:stdin:1:在主块[C]:在?
      • @PirateApp - 我没有看到你的程序。我的代码没有给出这样的错误。
      猜你喜欢
      • 2018-01-07
      • 1970-01-01
      • 2015-05-06
      • 2023-02-25
      • 2015-11-11
      • 2018-07-29
      • 1970-01-01
      • 2018-07-29
      • 1970-01-01
      相关资源
      最近更新 更多