Search code examples
arraysdictionarylua

What is the difference between indexing an array and a dictionary?


From my understanding, an array is a simple table of values, such as local t = {"a","b","c"}, and a dictionary is a table of objects, such as local t = {a = 1, b = 2, c = 3} Of course, let me know if I'm wrong in either or both cases.

Anyways, my question lies in how we index the entries in either of these cases. For example, let's say I have the following code:

local t = {"TestEntry"}
print(t["TestEntry"])

Of course, this prints nil. However, when we use a dictionary the same way:

local t = {TestEntry = 1}
print(t["TestEntry"])

This, naturally, prints 1. My question is, why does it work this way for dictionaries, but not arrays?

Finally, I'd like to address the issue that led me to this question. Let's say, before I want to run a chunk of code, I need to see if a specific value is inside a table. It would be convenient if I could just check if it is in the table with table["GivenEntry"], but, as we have seen, this would only work if the entry in the table is actually an object. In my specific case, I am simply using an array, so it is not an object.

Thus, I had to resort to using a for loop to check the table:

local t = {"TestEntry1","TestEntry2"}

for i,v in pairs(t) do
    if v == "TestEntry1" then
        --do code
    end
end

After doing this, it almost seemed as if it would be easier to create a silly dictionary, like:

local t = {TestEntry1 = "TestEntry1"}

because then, I could simply run t["TestEntry1"], and I wouldn't have to worry about having an empty table (because then the for loop would not run). Are there ramifications to creating a dictionary for such purposes? Is it less efficient in general?

Your input is appreciated, Thank you.


Solution

  • In Lua both arrays an dictionaries are the same type (the table). local t = {"TestEntry"} is essentially short for local t = {[1] = "TestEntry"} (The brackets are needed by Lua for a number, you would access it with t[1]).

    So the options for checking if "TestEntry1" is in the table are as you have written. A dictionary takes more memory and depending on how many values you have may take a while to create, but accessing a key should be constant time. Whereas to loop through the table will take longer and longer the more items you have so it is a tradeoff you have to decide on.

    There are faster ways to search an array however (e.g. if it is sorted: https://en.wikipedia.org/wiki/Binary_search_algorithm)