Naming dictionary keys numbers

I understand that when you define a dictionary with numbers, it is no longer a valid array structure so you will need pairs to iterate it. However, what about after you have defined the dictionary? In my case, I didn’t really think about this until now so Im wondering what would happen with everything I already did.
For Example,

local arr = *defined dictionary*
local value = 1

arr[value] = 2

In this scenario, I used a variable to define the key and the variable’s value is 1. Would it simply take the first value in the dictionary or would it set the key as 1?

Normally, I would think that the below example would show the second key in the dictionary.

local arr = *defined dictionary*
local value = 1

arr[2] = value

I would think I have a few options to solve my current problem of using numbers as the key. I could probably rename the keys or I could define all the keys with the original dictionary.

Now, does defining the key with a variable rather than the number straight away mean anything?

local arr = *defined dictionary*
local value = 1

arr[value] = 2
arr[2] = value
2 Likes

All tables in Lua are tables, “dictionary” and “array” are just interpretations of table structures used in various implementations including Lua’s own table class. If you have a dictionary like

local d = {a=1, b=2, c=3}

then add ordered numerical keys like

d[1] = 1
d[2] = 2
d[3] = 3

it is still a dictionary, however a lot of functions relying on arrays will still treat it like an array:

for i, v in ipairs(d) do --ipairs only works with arrays without nil values inbetween keys
    print(v) --prints 1, then 2, then 3
end

Your first example

local value = 1
arr[value] = 2

is exactly the same as writing arr[1] = 2. It would set the value of key 1 to 2, not the “first” key of the dictionary (the term “first” key does not make sense because dictionaries aren’t ordered).

No, this assigns the value (1) to the key 2, not the “second” entry of the dictionary.
If you want to change specific key-value pairs in a dictionary, you have to iterate through the table with pairs or know what the key is (all you have to do in that case is write arr.key = newValue).

2 Likes

Thanks for clearing this up. I had a completely different thought about numerical keys for so long.

1 Like