How do you copy a Lua 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

Consider the example shown below as reference −

 Live Demo

a = {}
a["name"] = "mukul"
a["age"] = 23
a["isWorking"] = true
function table.table_copy(t)
   local t2 = {}
   for k,v in pairs(t) do
      t2[k] = v
   end
   return t2
end
copy = table.table_copy(a)
for _,v in pairs(a) do print(v) end
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

mukul
true
23
mukul
true
23

Updated on: 20-Jul-2021

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements