Thats because that script is written very poorly. It is about 5 times longer than it needs to be (probably more than that), and has a lot of technical errors. There is no need for a global variable of for the names, and if so, no need to reinitialize it every time the the window is made. The other globals are even more useless.
Anyways, the problem is probably stemming from the variable not being right. It controls the index of the $WORLD array, and if it is a value with no matching index in the array, the return value is "nil", and then you get your error.