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
?
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.
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.
Lua's function , table , userdata and thread (coroutine) types are passed by reference.
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.
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).
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".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With