"Custom Value" is an unused integer only units have that you can define and access via trigger on a per-unit base (kind of like "unit point value", only that is has no effect on gameplay or the score screen. However, every unit has only one "Custom value", which is why it can only be used for one task per map.
This spawned the idea of creating a "unit indexer", which uses the custom value of units to assign a unique index for every unit for use in triggered spells and abilities in combination with array variables, as arrays only take integers as array index.
Sounds familiar? Correct. Because this is basicly
exactly what you are trying to do.
This data structure is called a "stack" in object orientated programming:
https://en.wikipedia.org/wiki/Stack_(abstract_data_type)
In pseudo code, it works like this (shamelessly editing IcemanBo's answer):
Trigger 1 (this one assigns an index for every unit on the map when the game starts):
Map Initialization:
Set MaxIndex = 0
PickAllUnitsInMapAndDoActions
---- Set MaxIndex = MaxIndex + 1
---- Set Unit[MaxIndex] = PickedUnit
---- Set Custom Value of Picked Unit = MaxIndex
Trigger 2 (this one cleans up dead units by swapping the last entry of the list with the one that was killed):
A unit dies:
Set Unit[Custom Value of Dying Unit] = Unit[MaxIndex]
Set Unit[MaxIndex] = No Unit
Set MaxIndex = MaxIndex - 1
Trigger 3 (this one automaticly adds newly created units):
A unit enters map rect:
---- Set MaxIndex = MaxIndex + 1
---- Set Unit[MaxIndex] = PickedUnit
However, it is highly recommended to use an existing Unit Indexer instead ... it will do all this automaticly for you and will also catch several corner cases you ignore with the implementation above.