Python dicts are now ordered
This is a refreshing update for those of us that like having code which will always act in the same way across multiple invocations.<p>Now, if only Lua could follow the same path with their “tables” (“tables” is what Lua programmers call their form of Python’s “dictionaries” and Perl’s “hashes”).<p>I just spent eight hours earlier this week debugging Lua code which would run differently on different invocations of the same code.<p>The standard way to iterate in a table with Lua is like this:<p><pre><code>  for key, value in pairs(foo) do
</code></pre>
One problem: The order we get elements from the table “foo” is undefined, and <i>it can change between different invocations of the same Lua code, even if the elements were put in the table in the same order</i>.  In order to fix things so that we can iterate a table in a consistent manner, this is my fix (public domain [1], if those who want to copy and paste it):<p><pre><code>  function sorted_table_keys(t)
    local a = {}
    local b = 1
    for k,_ in pairs(t) do -- pairs() use OK; will sort 
      a[b] = k
      b = b + 1
    end
    table.sort(a, function(y,z) return tostring(y) &lt; tostring(z) end)
    return a
  end
</code></pre>
Then we iterate the table like this:<p><pre><code>  for _, key in ipairs(sorted_table_keys(foo)) do
    local value = foo[key]
</code></pre>
(In Lua, two dashes indicates a comment.)<p>Note that this code will not always sort in the same order all tables.  If we have a table with the keys 1 (as a number) and &quot;1&quot; (as a string), iteration order is still undefined.<p>The code is open source, and is a procedural (“random”) map generator for Doom written mainly by Andrew Apted which I have added some features and fixed some bugs with.  It’s here: <a href="https:&#x2F;&#x2F;github.com&#x2F;samboy&#x2F;ObHack" rel="nofollow">https:&#x2F;&#x2F;github.com&#x2F;samboy&#x2F;ObHack</a> and the issue is here: <a href="https:&#x2F;&#x2F;github.com&#x2F;samboy&#x2F;ObHack&#x2F;issues&#x2F;4" rel="nofollow">https:&#x2F;&#x2F;github.com&#x2F;samboy&#x2F;ObHack&#x2F;issues&#x2F;4</a><p>[1] The project I added this code to is GPL, but this function, which I wrote entirely by myself, is one I am donating to the public domain.