On the main subject:
If you want a way to access the indexes in order and you also need to add and remove indexes without losing the order then the best way is to implement a binary search tree with the key values. In a binary search tree you can add and remove elements without having the sort the table every time. I have a simple implementation with an example in this thread:
http://us.battle.net/wow/en/forum/topic/11986218743#7
My example only deal with strings but it is possible to generalize it by passing a function that is able to determine the order between indexes (like comparing a number to a string and returning 1,0,-1 depending if the first argument should be considered greater, equal or lower than the second).
Lua Code:
--insert value in the binary tree
function BinarySearchTree.insert(tree_node,value,compare_values)
if tree_node==nil then
tree_node = {}
tree_node.value = value
tree_node.n = 1
elseif compare_value(tree_node.value,value)>0 then
tree_node.left = BinarySearchTree.insert(tree_node.left,value,compare_values)
tree_node.n = tree_node.n+1
elseif compare_value(tree_node.value,value)<0 then
tree_node.right = BinarySearchTree.insert(tree_node.right,value,compare_values)
end
return tree_node
end
--remove value from a binary tree
function BinarySearchTree.delete(tree_node,value,compare_values)
if tree_node then
if compare_value(tree_node.value,value)>0 then
tree_node.left = BinarySearchTree.delete(tree_node.left,value,compare_values)
tree_node.n = tree_node.n-1
elseif compare_values(tree_node.value,value)<0 then
tree_node.right = BinarySearchTree.delete(tree_node.right,value,compare_values)
elseif tree_node.left==nil and tree_node.right==nil then
tree_node = nil
elseif tree_node.left==nil and tree_node.right then
tree_node = tree_node.right
elseif tree_node.left and tree_node.right==nil then
tree_node = tree_node.left
else
tree_node.value = BinarySearchTree.get_min_value(tree_node.right)
tree_node.right = BinarySearchTree.delete(tree_node.right,tree_node.value,compare_values)
end
end
return tree_node
end
--get i-th element of the tree, m is just used on the recursion calls
function BinarySearchTree.get_element_i(tree_node,i,m)
m = m or 0
if tree_node==nil then
return nil
elseif tree_node.n+m==i then
return tree_node.value
elseif tree_node.n+m>i then
return BinarySearchTree.Get_element_n(tree_node.left,i,m)
else
return BinarySearchTree.Get_element_n(tree_node.right,i,m+tree_node.n)
end
end
function BinarySearchTree.get_min_value(tree_node)
if tree_node.left==nil then
return tree_node.value
else
return BinarySearchTree.get_min_value(tree_node.left)
end
end
function BinarySearchTree.max_value(tree_node)
if tree_node.right==nil then
return tree_node.value
else
return BinarySearchTree.get_max_value(tree_node.right)
end
end