Sam Trenholme's webpage
Support this website

Lua table iterator

 

March 9 2015

Let’s look at an interator which lists all of the keys of a Lua table in sorted order. Both string and numeric keys are allowed, and all string keys will be listed before all of the numeric keys.

==The code==

function sortedKeys(inTable)
  local keyList = {}
  local index = 1
  for k,_ in pairs(inTable) do
    table.insert(keyList,k)
  end
  -- Allow numbers and strings;
  -- strings before numbers
  local sf = function(a,b)
    if(type(a) == 'number'
       and
       type(b) == 'string')
    then
      return false
    elseif (type(b) == 'number'
            and
           type(a) == 'string')
    then
      return true
    end
    return a < b
  end
  table.sort(keyList, sf)
  return function()
    rvalue = keyList[index]
    index = index + 1
    return rvalue
  end
end

To run:

a = {hi="there"}
a[1] = "one"
a["one"] = "1string"
a["999"] = "three9s"
a[2] = "two"
for k in sortedKeys(a) do
  print(k,a[k])
end

This will output the following:

999     three9s
hi      there
one     1string
1       one
2       two

Strings are lexically sorted and numbers are numerically sorted. All strings come before all numbers. Unlike Javascript objects, in Lua, the number 1 and the string "1" can both be in the same table and are separate table keys.

Comments for blog entries can be seen in the forum.