Loop Through Records (code snippet)

Description

Simple loop using MoveToFirstRecord and MoveNext.

Requires: None

Code

Count all Individual Records

pi = fhNewItemPtr()  -- declare pointer 
pi:MoveToFirstRecord("INDI") -- and set to the first record.
iCount = 0
while pi:IsNotNull() do
   iCount = iCount + 1
   pi:MoveNext()
end
fhMessageBox('There are '..iCount..' people in the project')

Add All Individuals to a result set

local tblRecord = {} - declare table for output column
pi = fhNewItemPtr()  -- declare pointer 
pi:MoveToFirstRecord("INDI") -- and set to the first record.
while pi:IsNotNull() do
   table.insert(tblRecord,pi:Clone())   
   pi:MoveNext()
end
fhOutputResultSetTitles("All Individuals", "All Individuals", "Item List Example Date: %#x")
fhOutputResultSetColumn("Record", "item", tblRecord, #tblRecord, 140, "align_left")

Using an Iterator Function

Using Lua iterators makes the main code simpler and allow reuse as the records function only needs to be defined once and can be reused.

Function

Parameter is the record type to process.

function records(type)
    local pi = fhNewItemPtr()
    local p2 = fhNewItemPtr()
    pi:MoveToFirstRecord(type)
    return function ()
        p2:MoveTo(pi)
        pi:MoveNext()
        if p2:IsNotNull() then return p2 end
    end
end

Usage

for pi in records('INDI') do
    print (fhGetDisplayText(pi))
end