new to lua and I need some help figuring out the deepcopy process from the lua users wiki. Basically, I have an in ipairs table with multiple attributes per index chunk, and I want to copy the entire index chunk where the attributes meet certain if conditions, run in a for loop. Finally, I want to print the new table contents.
The table is very long so I'll just include a short excerpt.
local tblStudents = {
{
['Name'] = 'Jeff',
['Year'] = 'Twelve-A',
['Class'] = 'Ms Edwards',
['Attended'] = true
},
{
['Name'] = 'Tom',
['Year'] = 'Twelve-B',
['Class'] = 'Ms Edwards',
['Attended'] = true
},
{
['Name'] = 'Billy',
['Year'] = 'Twelve-A',
['Class'] = 'Ms Edwards',
['Attended'] = false
},
{
['Name'] = 'Jack',
['Year'] = 'Twelve-B',
['Class'] = 'Ms Edwards',
['Attended'] = false
},
{
['Name'] = 'Sam',
['Year'] = 'Twelve-A',
['Class'] = 'Mr Green',
['Attended'] = true
},
{
['Name'] = 'Diego',
['Year'] = 'Twelve-A',
['Class'] = 'Mr Green',
['Attended'] = false
},
{
['Name'] = 'Peta',
['Year'] = 'Twelve-A',
['Class'] = 'Mr Green',
['Attended'] = false
},
{
['Name'] = 'Will',
['Year'] = 'Twelve-A',
['Class'] = 'Ms Edwards',
['Attended'] = true
},
{
['Name'] = 'Sara',
['Year'] = 'Twelve-B',
['Class'] = 'Ms Edwards',
['Attended'] = true
},
{
['Name'] = 'Lisa',
['Year'] = 'Twelve-A',
['Class'] = 'Ms Edwards',
['Attended'] = true
}
}
What I want to do is deepcopy all of the students from Twelve-A who didn't attend to a new table, tblTruant I imagine the statement to do so would use the conditional:
for i,v in ipairs (tblStudents) do
if v.Year == 'Twelve-A' and v.Attended == false then
--deepcopy to new table.
The demo code I've been given for deepcopy is this:
local function deepCopy(original)
local copy = {}
for k, v in pairs(original) do
if type(v) == "table" then
v = deepCopy(v)
end
copy[k] = v
end
return copy
end
I'm not sure how to apply that using the conditional outlined above.
For printing the results of the new table, I've been told as I can't print a table as a string, to use this recursive function:
function dump(o)
if type(o) == 'table' then
local s = '{ '
for k,v in pairs(o) do
if type(k) ~= 'number' then k = '"'..k..'"' end
s = s .. '['..k..'] = ' .. dump(v) .. ','
end
return s .. '} '
else
return tostring(o)
end
end
My presumption would be that this would allow me to use print(dump(tblTruant) to get the desired result.
Any help greatly appreciated!