This function is very inefficient for large tables (O(n)) and should probably not be called in things that run each frame. Instead, consider a table structure such as example 2 below. Also see: Tables: Bad Habits
For optimization, functions that look for a value by sorting the table should never be needed if you work on a table that you built yourself.