…and if you take @nick_sherman’s approach and extrapolate it even further, perhaps to 10’s of thousands of records with dozens of fields, then don’t even hashtag your data fields, just imply them by position, and you’ll save both time and memory, fe:
-- field name forward lookup (ie, get name from index): local fieldNames = { "Name", "Age", "Address" } local data = { {"Tony", 35, "Bolton"}, {"Nigel", 56, "Ipswich"} } for recordNumber = 1, #data do for fieldNumber = 1, #fieldNames do -- "k" is NOT needed for RETRIEVAL at all -- provided only to have something for print() below local k = fieldNames[fieldNumber] local v = data[recordNumber][fieldNumber] print(k,v) end end
also fwiw, you might want a reverse lookup too:
-- field index reverse lookup (ie, get index from name): local fieldIndices = { Name=1, Age=2, Address=3 } for recordNumber = 1, #data do print(data[recordNumber][fieldIndices.Name] .. "'s age is " .. data[recordNumber][fieldIndices.Age]) end
if extending even further, perhaps 100 thousand records w hundred fields, then you might even want to break up the table into discrete indexed arrays of Name[n], Age[n], Address[n]. (bc each record takes 36 bytes, each hash take 40 bytes, while a numeric index just 16) But… you would NOT want to do that if deletion (rather than storage/retrieval) is your primary concern!!
(also note that memory usage is heavier for a dynamically allocated table, compared to these static initialized examples)