How to keep the order of a Lua table with string keys?

Hi all. Please tell me how to save the positions of the keys in the table.

lua constantly changes them - but for me it is critical

i need

{ --[[00000000028084D0]]
  first = { --[[0000000002809410]]
    any sub tables
  },
  second = { --[[00000000028085F0]]
    any sub tables
  },
  third = { --[[0000000002809DF0]]
    any sub tables
  }
}

but i have

{ --[[00000000028084D0]]
  third = { --[[0000000002809410]]
    any sub tables
  },
  first = { --[[00000000028085F0]]
    any sub tables
  },
  second = { --[[0000000002809DF0]]
    any sub tables
  }
}

i try sort - this not work and create temp table and insert after - not work. Allways random key position

function func.robots_array_align(array)
	
	--pprint(array)

	for user_id, user in pairs(array.users) do

		local sort = array.users[user_id].robots

		pprint('unsorted')
		pprint(sort)
		table.sort(sort)
		pprint('sorted')
		pprint(sort)
		
		array.users[user_id].robots = sort
		
		--pprint(sort)
		
		--[[local temparr = {}
		
		if user.robots.third ~= nil then 
			--temparr['third'] = user.robots.third
			table.insert(temparr, 3, {third = user.robots.third})
		end
		
		if user.robots.second ~= nil then 
			--temparr['second'] = user.robots.second
			table.insert(temparr, 2, {second = user.robots.second})
		end
		
		if user.robots.first ~= nil then 
			--temparr['first'] = user.robots.first
			table.insert(temparr, 1, {first = user.robots.first})
		end

		array.users[user_id].robots = nil
		array.users[user_id].robots = temparr
		pprint(temparr)
		temparr = nil]]--
		
	end

	--pprint(array)
	
	return array
end
1 Like

You can only rely on the order of integer indexed tables, how you work with that is up to you.

I’m sure there are many ways. This is what I would do.

{
    {id="First", subtables={}},
    {id="Second", subtables={}},
}

Accessing the table in order is then easy. Accessing by id would require a helper function that iterates over the table.

3 Likes

Thank you for your reply.

Very bad. Very strange. Not optimal (( Strange language
Violates data integrity. Unpredictable outcome

Well, the Lua tables are “hash tables”, and as such the keys are “unsorted”.

You’ll find the same behavior in most languages, unless it’s specifically an “ordered hash table”, where special care has been taken to preserve the insertion order.

3 Likes

:crying_cat_face:

I wonder, why do you specifically need the key to be first, second, third and can’t be 1,2,3? :slightly_smiling_face:

too late, a lot of rewriting in the back end.

but it doesn’t matter, I solved the problem. turned out even better))

1 Like

Initially, it seemed to me that the structure of the transmitted data would be too complicated. And in order not to get confused, I used string keys - but lua screwed up (((