Game Development Reference
In-Depth Information
return theValue
else
return {theValue}
end
end
Sorting on Elements of a Table
The table.sort function is a very handy function for sorting tables with single dimensions and
that have numeric or string values. If we were given a table that was a record with the structure as
follows, the generic sort function would not work:
{
name = "Jayant",
subject = "IT",
grade = "A"
}
We might want to sort these records according to one of the three fields: grade , name , or subject . As
this is sorting on more than one dimension, the sort function would not work.
We sort a table using the function table.sort(theTable, functionToSort) . In the case of this
example, we can use
function sortOnField(theTable, theField)
table.sort(theTable,
function(a,b)
return a[theField] < b[theField]
end)
end
If the table is a multidimensional array, you can simply pass the dimension instead of the field name,
and it should work.
Determining Frequency of an Item in a Table
The table can be used as a storage space. For example, you could save all the items that the player
collects during the game to be used in calculating an end-of-level score, using a multiplier based on
the collected items. To do so, you might want to know how many items of a particular type there are
in the table. If these were plain numbers, you might want to know the frequency of the numbers in
the table.
function getCount(theTable, theValue)
local count = 0
for i,j in pairs(theTable)
if j == theValue then
count = count + 1
end
end
return count
end
 
Search WWH ::




Custom Search