Concatenation of tables in Lua

后端 未结 9 791
难免孤独
难免孤独 2020-12-09 15:04

ORIGINAL POST

Given that there is no built in function in Lua, I am in search of a function that allows me to append tables together. I have google

相关标签:
9条回答
  • 2020-12-09 15:34

    If you want to concatenate an existing table to a new one, this is the most concise way to do it:

    local t = {3, 4, 5}
    local concatenation = {1, 2, table.unpack(t)}
    

    Although I'm not sure how good this is performance-wise.

    0 讨论(0)
  • 2020-12-09 15:38

    Here is my implementation to concatenate a set of pure-integer-indexing tables, FYI.

    1. define a function to concatenate two tables, concat_2tables
    2. another recursive function concatenateTables: split the table list by unpack, and call concat_2tables to concatenate table1 and restTableList

      t1 = {1, 2, 3}
      t2 = {4, 5}
      t3 = {6}
      
      concat_2tables = function(table1, table2)
          len = table.getn(table1)
          for key, val in pairs(table2)do
              table1[key+len] = val
          end
          return table1
      end
      
      concatenateTables = function( tableList )
          if tableList==nil then
              return  nil
          elseif table.getn(tableList) == 1 then
              return  tableList[1]
          else
              table1 = tableList[1]
              restTableList = {unpack(tableList, 2)}
              return concat_2tables(table1, concatenateTables(restTableList))
          end
      end
      
      tt = {t1, t2, t3}
      t = concatenateTables(tt)  
      
    0 讨论(0)
  • 2020-12-09 15:40

    If you want to merge two tables, but need a deep copy of the result table, for whatever reason, use the merge from another SO question on merging tables plus some deep copy code from lua-users.

    (edit Well, maybe you can edit your question to provide a minimal example... If you mean that a table

     { a = 1, b = 2 }
    

    concatenated with another table

    { a = 5, b = 10 }
    

    should result in

    { a = 1, b = 2, a = 5, b = 10 }
    

    then you're out of luck. Keys are unique.

    It seems you want to have a list of pairs, like { { a, 1 }, { b, 2 }, { a, 5 }, { b, 10 } }. You could also use a final structure like { a = { 1, 5 }, b = { 2, 10 } }, depending on your application.

    But the simple of notion of "concatenating" tables does not make sense with Lua tables. )

    0 讨论(0)
提交回复
热议问题