Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

Is there an easy way to add one table to another?

Asked by 5 years ago

I have two tables which I want to create an item for everything in those tables. To make it simple I want to put both the tables into one table. Is there an easier way than doing this:

local tableOne = {1, 2, 3}
local tableTwo = {4, 5, 6}

for i,v in pairs(tableOne) do
    table.insert(tableTwo, v)
end


I know this way seems easy but so is the pure Lua implementation of :FindFirstChild() and we still use :FindFirstChild(). Hope you can help. Thanks!

0
Use table.concat or something Griffi0n 315 — 5y

1 answer

Log in to vote
1
Answered by
ozzyDrive 670 Moderation Voter
5 years ago
Edited 5 years ago

You can write your own function to do just that. I personally often use a module that I can require in all of my scripts and overwrite the 'table' variable with to extend the native table library with my own functions.

local table = setmetatable({}, {__index = table})

table.combine = function(...)
    local arrays = {...}
    local newArray = {}
    for i = 1, #arrays do
        for j = 1, #arrays[i] do
            newArray[#newArray + 1] = arrays[i][j]
        end
    end
    return newArray
end

--

--  If the above was a module, you would overwrite the global table variable:
--  local table = require(tableModule)


local a = {1, 2, 3}
local b = {4, 5, 6}
local c = {7, 8, 9}

print(table.concat(table.combine(a, b, c)))

0
Thanks User#21908 42 — 5y
Ad

Answer this question