Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you copy a Lua table by value?

Tags:

lua

lua-table

Recently I wrote a bit of Lua code something like:

local a = {} for i = 1, n do    local copy = a    -- alter the values in the copy end 

Obviously, that wasn't what I wanted to do since variables hold references to an anonymous table not the values of the table themselves in Lua. This is clearly laid out in Programming in Lua, but I'd forgotten about it.

So the question is what should I write instead of copy = a to get a copy of the values in a?

like image 931
Jon Ericson Avatar asked Mar 12 '09 21:03

Jon Ericson


People also ask

How do I unpack a table in Lua?

unpack() function in Lua programming. When we want to return multiple values from a table, we make use of the table. unpack() function. It takes a list and returns multiple values.

What is a table value Lua?

Lua uses tables to represent packages as well. When we write io. read , we mean "the read entry from the io package". For Lua, that means "index the table io using the string "read" as the key". Tables in Lua are neither values nor variables; they are objects.

Is Lua pass by reference?

Lua's function , table , userdata and thread (coroutine) types are passed by reference.

How does Lua tables work?

Lua uses a constructor expression {} to create an empty table. It is to be known that there is no fixed relationship between a variable that holds reference of table and the table itself. When we have a table a with set of elements and if we assign it to b, both a and b refer to the same memory.


2 Answers

Table copy has many potential definitions. It depends on whether you want simple or deep copy, whether you want to copy, share or ignore metatables, etc. There is no single implementation that could satisfy everybody.

One approach is to simply create a new table and duplicate all key/value pairs:

function table.shallow_copy(t)   local t2 = {}   for k,v in pairs(t) do     t2[k] = v   end   return t2 end  copy = table.shallow_copy(a) 

Note that you should use pairs instead of ipairs, since ipairs only iterate over a subset of the table keys (ie. consecutive positive integer keys starting at one in increasing order).

like image 126
Doub Avatar answered Sep 24 '22 15:09

Doub


Just to illustrate the point, my personal table.copy also pays attention to metatables:

function table.copy(t)   local u = { }   for k, v in pairs(t) do u[k] = v end   return setmetatable(u, getmetatable(t)) end 

There is no copy function sufficiently widely agreed upon to be called "standard".

like image 21
Norman Ramsey Avatar answered Sep 21 '22 15:09

Norman Ramsey