Is there a way to change a dictionary table into an array table?

I’m using table.insert and a for loop to put items into a table. It automatically puts it as a dictionary though. Is there a way to put it as an array or transform into an array?
Dictionary Table

local dictionary = {
   [1] = "One",
   [2] = "Two",
   [3] = "Three",
}

Array Table

local array {
   "One",
   "Two",
   "Three",
}

If not, is there a way to find a value instead of the key?
For example,

print(dictionary[1]) -- this would print "One"

dictionary[One] --This would give an error but this is what I want to do

Thanks!

1 Like

I think you’re confused. First, some explanation: All arrays are dictionaries, but not all dictionaries are arrays. Arrays is when a dictionary has integers as the index (also called key) that starts at one and counts by one. A table in Lua can be a combination of an array and a dictionary; in other words, dictionary is a superset of array.

When you define a table without the index, it is implied to be an array. These two tables are equivalent:

{1, 2, 3}
{[1] = 1, [2] = 2, [3]}

And so are these two:

{1, 2, c = 'c'}
{[1] = 1, [2] = 2, ['c'] = 'c'}

A table in Lua can only have one array. If there is a gap in the array, then it will simply be truncated.

print(#({1, 2, 3})) --> 3
print(#({1, 2, nil, 4})) --> 2

You are talking about hashmaps, which, are still just dictionaries! Hashmaps are like the opposite of an array; the values are stored within the index itself. See the difference:

{ --array
    'Apple',
    'Banana',
    'Orange',
}

{ --hashmap
    Apple=true,
    Banana=true,
    Orange=true,
}

And all you need to do is index the hashmap with the value itself to see if it exists in the table:

local t = {Apple=true, Banana=true, Orange=true}
print(t['Apple']) --> true
print(t.Banana) --> true
print(t.Grapefruit) --> nil (doesn't exist)

Tables in Lua can accept anything other than nil as the index. This means you can also use Instances, functions, even other tables in a hashmap:

local t = {}
t[workspace.Part] = true

print(t[workspace.Part]) --> true

But be careful when you index them with tables. A table is only equivalent to itself, so you cannot index with a similar table; it needs to be the same exact one.

local t = {}
local key = {1, 2, 3}
t[key] = true

print(t[key]) --> true
print(t[{1, 2, 3}]) --> nil
2 Likes

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