The order of table keys in Lua is random?

Not sure if this is a JIT topic or normal behaviour in lua, but I think I remember it was different before. Given this structure

defaultConfig = {
  convertToRedux = true,
  exportVST2 = false,
  exportVST3 = true,
}

will give you a random order if queried with pair() like
for key, value in pairs(defaultConfig) do ... end

Some libraries seem to assume that the sequence keeps like it was added.

Is this kind of order randomization preventable?

That’s how it works in every lua version afaik.

https://www.lua.org/pil/19.3.html

1 Like

Maybe the simplest: Just internally store the data as [1] = { key = “convertToRedux”, value = “true” } and it will be iterable (ipairs!).

2 Likes

Mmh, I would expect non-random behaviour from a scripting language, just as all the other languages do, too… Yeah, but it is like it is, isn’t it?

Just because it’s not random in some languages doesn’t mean you should ever rely on it. You’re betting on the data structure’s hash function to never change, which I don’t think most language implementers are willing to guarantee. Typically you should use some kind of ordered map if the language provides it. As Lua doesn’t, @joule’s solution is the best way.

All I say is this: such a non deterministic behaviour has no practical use and can be considered as a design flaw. A programming language should always focus on its practical use. Let’s take JavaScript, of course orders in object structures are kept intact, and it still is blazingly fast. I will fill in a bug report at lua.org… not!

This still might work as you might receive their reply before you send the report!

1 Like

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.