How to check bool nested in table in lua

Viewed 254

I'm new to lua, and I'm having trouble with a basic sort-by-bool-condition thing for entries in a table.

`local tblFormReturn = {
    {
        ['Name'] = 'Spike',
        ['Year'] = '10',
        ['House'] = 'Holmes',
        ['Form Returned'] = true
    },
    {
        ['Name'] = 'Elvis',
        ['Year'] = '11',
        ['House'] = 'Shaw',
        ['Form Returned'] = true
    },
    {
        ['Name'] = 'Michael',
        ['Year'] = '10',
        ['House'] = 'Langley',
        ['Form Returned'] = false
    },
    {
        ['Name'] = 'Chang',
        ['Year'] = '11',
        ['House'] = 'Holmes',
        ['Form Returned'] = false
    }
}`

Basically, I want to be able to take this table, and for each chunk, check whether the kid is in Holmes house (1) and if they have returned their form (2). My feeling is I need to run a for-loop in pairs based off the lua manual, but I'm confused as to how I can access these values, given each chunk is sort of a sub-table. My attempts have all been based around something like this.

for i,'Form Returned' in tblFormReturned('Form Returned') do
    if 'Form Returned' == true then
        if 'House' == 'Holmes' then
            print ('Number of Holmes forms returned' +1)
            end
        end
    end

I'm not sure how to make this work. Any help greatly appreciated.

1 Answers

A few things of note here.

When you quote something (indicated by using the single quotes), you effectively make it a string.

A for loop loops through a table using ipairs (indexed pairs, such as yours is) or pairs (used on dictionary tables). Dictionary tables are considered those that are have a defined key rather than an index key (e.g. tblPets = {dog = "Fido", cat = "Sassy", duck = "Quackers} - this would allow you to return tblPets.dog (or tblPets["dog"]) to get the value).

Your print statement to add a number does not work. You cannot add a number to a string. Instead, you will need to set a count as a variable and add to it, provided it is a number.

Lastly, you can also combine the if statements into one to make it easier.

formCount = 0 -- This initializes the variable formCount as an interger, starting with 0.
for i,v in ipairs(tblFormReturned) do -- This iterates through the table
    if v["Form Returned"] and v.House == "Holmes" then -- Looks to see if the form returned is true and house is Holmes. Note that with boolean values, you do not have to see if it equals true or false. if v["Form Returned"] == true and this format returns the same answer.
        formCount = formCount + 1 -- Adds 1 to the formCount
    end -- end if statement
end -- end for loop

Hopefully this helps a little with understanding. If you have any questions, don't hesitate to ask for clarification.

Related