Sorting By Functions in UnrealScript
Sometimes we’ll want to sort a collection by something other than its natural order. For example, suppose we wanted to sort strings by their length instead of alphabetically. Here’s an example of custom sorts in UnrealScript.
class SortingByFunctions extends Object;
struct Person
{
var string Name;
var int Age;
};
static function SortStringsByLength(out array<string> StringArray)
{
local int i, j;
local string Temp;
for (i = 0; i < StringArray.Length - 1; i++)
{
for (j = 0; j < StringArray.Length - i - 1; j++)
{
if (Len(StringArray[j]) > Len(StringArray[j + 1]))
{
Temp = StringArray[j];
StringArray[j] = StringArray[j + 1];
StringArray[j + 1] = Temp;
}
}
}
}
static function SortPeopleByAge(out array<Person> PeopleArray)
{
local int i, j;
local Person Temp;
for (i = 0; i < PeopleArray.Length - 1; i++)
{
for (j = 0; j < PeopleArray.Length - i - 1; j++)
{
if (PeopleArray[j].Age > PeopleArray[j + 1].Age)
{
Temp = PeopleArray[j];
PeopleArray[j] = PeopleArray[j + 1];
PeopleArray[j + 1] = Temp;
}
}
}
}
static function ExecuteExample()
{
local array<string> Fruits;
local array<Person> People;
local Person TempPerson;
local int i;
// Initialize fruits array
Fruits.AddItem("peach");
Fruits.AddItem("banana");
Fruits.AddItem("kiwi");
// Sort fruits by length
SortStringsByLength(Fruits);
// Print sorted fruits
`log("Sorted fruits by length:");
for (i = 0; i < Fruits.Length; i++)
{
`log(Fruits[i]);
}
// Initialize people array
TempPerson.Name = "Jax";
TempPerson.Age = 37;
People.AddItem(TempPerson);
TempPerson.Name = "TJ";
TempPerson.Age = 25;
People.AddItem(TempPerson);
TempPerson.Name = "Alex";
TempPerson.Age = 72;
People.AddItem(TempPerson);
// Sort people by age
SortPeopleByAge(People);
// Print sorted people
`log("Sorted people by age:");
for (i = 0; i < People.Length; i++)
{
`log(People[i].Name @ "(" $ People[i].Age $ ")");
}
}
In this UnrealScript example, we implement custom sorting functions for both strings (by length) and a custom Person
struct (by age). UnrealScript doesn’t have built-in sorting functions like Go’s slices.SortFunc
, so we implement a simple bubble sort algorithm for both cases.
The SortStringsByLength
function sorts an array of strings based on their length. The SortPeopleByAge
function sorts an array of Person
structs based on their age.
In the ExecuteExample
function, we demonstrate how to use these sorting functions:
- We create and sort an array of fruits by their name length.
- We create and sort an array of
Person
structs by their age.
Note that UnrealScript uses log
statements for output, which is equivalent to fmt.Println
in the original Go code.
To run this code, you would typically include it in an UnrealScript class and call the ExecuteExample
function from somewhere in your game logic. The output would be visible in the Unreal Engine log.