Lua - Copy Table by Value



Copying a table means that we want all the values or pairs that are present in one table in another table. In Lua, there's no standard library function that we can use to create such a table but we can create our own function to do so.

Let's create a function in Lua that will take a table as an argument and will create a new table that will be the exact copy of the table passed as an argument to the function.

Example - Copy Table by Value

Consider the example shown below as reference −

main.lua

-- initialize an empty array
a = {}

-- add values to the array
a["name"] = "mukul"
a["age"] = 23
a["isWorking"] = true

-- function to copy table 
function table.table_copy(t)
   local t2 = {}
   -- iterate the array
   for k,v in pairs(t) 
   do
      t2[k] = v
   end
   return t2
end

-- copy the table
copy = table.table_copy(a)

-- iterate the array and print values
for _,v in pairs(a) 
do 
   print(v) 
end

-- iterate the copied array and print values
for _,v in pairs(copy) 
do 
   print(v) 
end

In the above example, we have a table named a which we later pass as an argument to the function named table.table_copy() and that function returns us a copy of the same table that we passed and finally I printed the values inside these tables to check whether the copied table is accurate or not.

Output

When we run the above code, we will get the following output−

mukul
true
23
mukul
true
23
Advertisements