【问题标题】:Lua table.concatLua 表.concat
【发布时间】:2013-03-06 20:02:27
【问题描述】:

有没有办法用table.concat的arg 2值来表示当前表的索引?

例如:

 t = {}
 t[1] = "a"
 t[2] = "b"
 t[3] = "c"

 X = table.concat(t,"\n")

table concat (X) 的期望输出:

 "1 a\n2 b\n3 c\n"

【问题讨论】:

    标签: lua concatenation lua-table


    【解决方案1】:

    我不这么认为:例如,您如何告诉它键和值之间的分隔符应该是空格?

    你可以编写一个通用的映射函数来做你想做的事:

    function map2(t, func)
      local out = {}
      for k, v in pairs(t) do
        out[k] = func(k, v)
      end
      return out
    end
    
    function joinbyspace(k, v) 
      return k .. ' ' .. v 
    end
    
    X = table.concat(map2(t, joinbyspace), "\n")
    

    【讨论】:

      【解决方案2】:

      简单的回答:没有。

      table.concat 是非常基本的东西,而且非常快。

      所以无论如何你都应该循环执行。

      如果你想避免过多的字符串连接,你可以这样做:

      function concatIndexed(tab,template)
          template = template or '%d %s\n'
          local tt = {}
          for k,v in ipairs(tab) do
              tt[#tt+1]=template:format(k,v)
          end
          return table.concat(tt)
      end
      X = concatIndexed(t) -- and optionally specify a certain per item format
      Y = concatIndexed(t,'custom format %3d %s\n')
      

      【讨论】:

      • 没错,谢谢。顺便说一句,如果您发现这样的错误,请随时自行编辑答案,因为您有足够的权限进行编辑。
      【解决方案3】:

      没有。但是有一个解决方法:

      local n = 0
      local function next_line_no()
         n = n + 1
         return n..' '
      end
      
      X = table.concat(t,'\0'):gsub('%f[%Z]',next_line_no):gsub('%z','\n')
      

      【讨论】:

        【解决方案4】:
        function Util_Concat(tab, seperator)
          if seperator == nil then return table.concat(tab) end
          local buffer = {}
          for i, v in ipairs(tab) do
            buffer[#buffer + 1] = v
            if i < #tab then
              buffer[#buffer + 1] = seperator
            end
          end
          return table.concat(buffer)
        end
        

        用法 tab 是表格输入的位置,分隔符既是 nil 或字符串(如果它是 nil 它就像普通的 table.concat

        print(Util_Concat({"Hello", "World"}, "_"))
        --Prints
        --Hello_world
        

        【讨论】:

          猜你喜欢
          • 2011-04-08
          • 1970-01-01
          • 2016-04-08
          • 2015-04-30
          • 2021-12-21
          • 2011-05-30
          • 1970-01-01
          • 2015-03-14
          • 2017-07-25
          相关资源
          最近更新 更多