As piglet pointed out, you can use temporarily tables, like he showed in his example. The reference to the table inside of the function will be lost after the function, so the only way to access newEntry
is via the main table.
However, if you really need to copy (really copy) the table, you need to use a function for this. But keep in mind that you often don't have to copy.
In this answer, a very short deepcopy method for tables is shown. This can be used to make two tables independent of each other. This also handles some other stuff like metatables. Additionally, the answer gives some links to further readings.
I would suggest to you to make use of the penlight library for lua, a non-official 'standard' library which is very useful. It has a rich documentation including guides to show what you can use penlight for. In your case, it provides a deepcopy function, so it all comes down to this:
local tablex = require "pl.tablex"
local tempTable = {}
-- more code
local mainTable = {}
-- more code
table.insert(mainTable, tablex.deepcopy(tempTable))
At last, a little advice on lua syntax: A part of lua origins in a data description language, so it is possible to write such things down very easy and nice:
TempTable = {
date = { day, month, year },
name = "Name Here",
address = "Address Here", -- you can put a comma AFTER the last element
}
Now using the function approach, you could pack everything up very nicely:
function create_entry(name, address, date)
local date = date or get_current_date() -- use date parameter or the current date if absent
return {
name = name,
address = address,
date = date
}
end
-- can be used like this:
table.insert(mainTable, create_entry("Foibudle", "12345 Dreamland", date("12-03-2015"))
-- can be used without the date:
table.insert(mainTable, create_entry("Foibudle", "12345 Dreamland")