You could do this by keeping an untouched copy of the initial table somewhere then copy all of it's elements to a new table:
local table = { "InitialValue1", "InitialValue2" }
local function copyTable(tableToCopy)
local newTable = {}
for i, v in pairs(tableToCopy) do
newTable[i] = v
end
return newTable
end
local function removeElement(table, index)
table.remove(table, index)
if #table == 0 then
if #newTable == 0 then
newTable = copyTable(table)
end
end
end
local newTable = copy(table)
removeElement(removeElement, 2)
removeElement(removeElement, 1)
for i, v in pairs(newTable) do
print("newTable[" .. i .. "] = " .. tostring(v))
end
Note that in this example comparing table with newTable, E.g:
if table == newTable then
end
Will always return false because tables are compared by reference.
This topic is a bit more advanced for this answer but basically, every variable has a value and an unique address location in the computer's memory. To comparing tables (unlike numbers, strings and the nil value) is to compare their addresses instead of their value. Since each table has its own unique address, and since they are compared by address, comparing two variables with table values serve to know whether the two variables point to the same table in memory.
About References:
A variable that points to a value is known as a reference or a pointer. The difference between a reference and a value-type is that since multiple references can point to the same block of memory (to the same value in memory), then modifying the value through one reference (or pointer) will replicate the changes to any other reference. To simplify:
local foo = {}
local bar = foo
foo[1] = "Hello, World!"
print(bar[1])
For the same reason, you cannot copy a table by simply assigning a variable to it (E.g: local newTable = table); since it is passed by reference instead of by value.
Hope this helps. If it does, please make sure to vote the answer up and to accept it. :)
If you need anything else, feel free to leave me a message.
1 comment
Make a backup table and set the contents of the backup table to that of the table that gets its values removed.