Back to OmaTips

Sorting Lists
Lists are sorted alpha-numerically. This presents problems when you want lists to store information according to purely numeric values.

Say you want a list of trade post items, sorted by the cost of the item (making this up):
/listadd {TradeItems}
/itemadd {TradeItems} {1 a widget}
/itemadd {TradeItems} {3 grain of rice}
/itemadd {TradeItems} {7 box of jujubees}
/itemadd {TradeItems} {10 glass of water}
/itemadd {TradeItems} {27 a wooden coffin}

Ok we've entered in the data, but hrm the list sorts like this!:
001: 1 a widget
002: 10 glass of water
003: 27 a wooden coffin
004: 3 grain of rice
005: 7 box of jujubees

Obviously nothing's sorted by value. So, we need to @PadLeft() the numbers, then tack on the item name. If all numbers are justified equally, the list will sort!
/itemadd {TradeItems} {@PadLeft(1, ,2) a widget}
/itemadd {TradeItems} {@PadLeft(3, ,2) grain of rice}
/itemadd {TradeItems} {@PadLeft(7, ,2) box of jujubees}
/itemadd {TradeItems} {@PadLeft(10, ,1) glass of water}
/itemadd {TradeItems} {@PadLeft(27, ,1) a wooden coffin}

And we now have a nice sorted list:
001:   1 a widget
002:   3 grain of rice
003:   7 box of jujubees
004:  10 glass of water
005:  27 a wooden coffin

You can automate the @PadLeft() without having to manually enter the "pad with xx characters". Trick is to make sure you're padding enough times so that any string you are padding will get padded.
That is, say you're padding the trade values. And you "know" the max value is like "1000". That's 4 characters, eg: @Len(1000)=4. So it's safe to pad 4 or more characters. Typically I go 1 over the max length that I (assume) I'll get. So let's use 5 as the pad count value, assuming the max length of any value via this script will be 4.

/action {whatever %0 value spew} {/itemadd {TradeItems} {@PadLeft($0, ,@Math(5-@Len($0)))}}
That'll pad "$0" over with 5 spaces, but less the length of the variable "$0". So if the value was say 56, the script would be doing:
/itemadd {TradeValue} {@PadLeft(56, ,@Math(5-2))} ...which is really:
/itemadd {TradeValue} {@PadLeft(56, ,3)} ..which is really:
/itemadd {TradeValue} {   56}

When all the values go in, they are padded with 5, less the length. So they're all justified equally. Hence you get a nice sorted list by value, instead of just numerically.