Trying to print the number of entries that have 'Spotted' as true within this table

Viewed 41

I am attempting to learn Lua and a friend of mine has given me some code to help me learn tables and table manipulation and I am currently having issues with doing the following with this table he has given me.

  1. Write a program to count how many spotted dogs are in the table.
  2. Write a program to count how many of each breed there are.
  3. Write a program to invert all of the 'Spotted' in a new table called tblSpottedDogs

He has given me some hints for 3, which I'll attempt when I get to it, so that is less of an issue for now, but 1 and 2 I am having issues with.

local tblDogs = {
    {
        ['Name'] = 'Jeffey',
        ['Breed'] = 'Jack Russell Terrier',
        ['Colour'] = 'White and Black',
        ['Spotted'] = true
    },
    {
        ['Name'] = 'Spot',
        ['Breed'] = 'Jack Russell Terrier',
        ['Colour'] = 'White and Brown',
        ['Spotted'] = false
    },
    {
        ['Name'] = 'Jeffey',
        ['Breed'] = 'Jack Russell Terrier',
        ['Colour'] = 'White and Red',
        ['Spotted'] = true
    },
    {
        ['Name'] = 'Snitzel',
        ['Breed'] = 'Dachshund',
        ['Colour'] = 'Brown',
        ['Spotted'] = false
    },
    {
        ['Name'] = 'Hugo',
        ['Breed'] = 'Dachshund',
        ['Colour'] = 'Dark Brown',
        ['Spotted'] = false
    },
    {
        ['Name'] = 'Freedum',
        ['Breed'] = 'Eagle',
        ['Colour'] = 'Brown Feathers',
        ['Spotted'] = true
    },
    {
        ['Name'] = 'Grrrrrrrrrrrrrrrrrrrrrrrr',
        ['Breed'] = 'Bear',
        ['Colour'] = 'Brown',
        ['Spotted'] = false
    },
    {
        ['Name'] = 'Stinky',
        ['Breed'] = 'Skunk',
        ['Colour'] = 'White and Black',
        ['Spotted'] = false
    },
    {
        ['Name'] = 'Gary',
        ['Breed'] = 'Golden Retriever',
        ['Colour'] = 'Golden Yellow',
        ['Spotted'] = false
    },
    {
        ['Name'] = 'Stinky',
        ['Breed'] = 'Cat in the Hat',
        ['Colour'] = 'Cat',
        ['Spotted'] = false
    }
}
2 Answers

Start with this code, which traverses the table and prints some selected fields.

for _,d in ipairs(tblDogs) do
    print(d.Name,d.Spotted)
end

Some tips, without spoiling everything for you:

-- Check for spotted dogs.
for i = 1, #tblDogs do
 if tblDogs[i]["Spotted"] then
  print("Do your accumulation here");
 end
end

-- Loop table backwards and check for spotted dogs.
for i = #tblDogs, 1, -1 do
 if tblDogs[i]["Spotted"] then
  print("Add " .. tblDogs[i]["Name"] .. " to a new table");
 end
end
Related