-
Notifications
You must be signed in to change notification settings - Fork 23
Comparators
Person8880 edited this page Jan 16, 2016
·
4 revisions
Comparators are an often hit and somewhat repetitive problem for sorting. Shine includes a simple set of comparator objects that can get rid of the most frequent comparator logic.
The available comparator types are:
-
Field
- Compares by a field on the table's values, with an optional default value. -
Method
- Compares by calling a method on the table's values, and optionally passing an argument and transforming the result. -
Composition
- Composes any number of comparators so that the sorting is performed from least to most important comparison result.
To get a comparator:
local Comparator = Shine.Comparator( Type, ... )
Here, type is one of the string types listed above. The remaining arguments depend on the comparator type.
Once setup, you can get the comparison function for passing into table.sort()
by calling Comparator:Compile()
. For example:
-- Compares by the "Name" field in ascending order (1 means ascending).
local NameComparator = Shine.Comparator( "Field", 1, "Name" )
-- Compares by the "Immunity" field in descending order (-1 means descending). If a value has no "Immunity" field, then it's taken to be 0.
local ImmunityComparator = Shine.Comparator( "Field", -1, "Immunity", 0 )
-- Returns a composition comparator, that first compares by immunity, then by name.
local Comparator = Shine.Comparator( "Composition", NameComparator, ImmunityComparator )
-- Compile the comparator and sort.
table.sort( Table, Comparator:Compile() )
If you want to use the comparator in table.MergeSort()
, then use Comparator:CompileStable()
instead.