Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
1

Does indexing a table return that values position in the table?

Asked by 7 years ago

For instance,

local Table = {"Pie", "Bacon", "Eggs", "Milk"}

print(tostring(Table["Pie"]))

Would this print "1" or something else?

1 answer

Log in to vote
0
Answered by 7 years ago
Edited 7 years ago

Your table index would yield nil. Here's why...

Sorted arrays

Your table doesn't have any specific key : value pairs. It's numerically sorted. For example, Pie is the first element, Bacon is the second element, and so on. Since no keys were assigned to those values, the key is automatically their position in the array.


You could make it easier to visualize by manually assigning the position as their key, though this is redundant in any applicable situation since it's done automatically.

local t = {
    [1] = "Pie";
    [2] = "Bacon";
    [3] = "Eggs";
    [4] = "Milk";
}

The table above is the exact same as the one in your snippet, except we're just showing how the table really looks behind the scenes. If you wanted to index the table for Pie, you'd just use it's position in the table like such t[1]

Likewise, you could create a new index by choosing the key in the table you want to overwrite. The syntax would be no different from creating any ordinary variable:

local t = {}
t[1] = "Pie"
t[2] = "Bacon"
t[3] = "Eggs"
t[4] = "Milk"

Again, the code above is no different than the table in your snippet apart from format.

Hash tables

Any non-numerically sorted keys in a table is automatically considered a hash table (or a mixed table, if both formats are being used). Hash tables would be indexed similarly, except you'd use the generic key associated with the value you want instead of a number representing that value's position. For instance...

local t = {
    ["Pie"] = 1;
    ["Bacon"] = 2;
    ["Eggs"] = 3;
    ["Milk"] = 4;
}

The values in this table are no longer in order (not even the order you see them in). Therefore, attempting to use our previous solution for retrieving values from an array are no longer acceptable. Such an attempt like t[1] would yield nil. This is where you could index the table with a generic key. For example, t["Pie"] or t.Pie would yield the value 1

0
Ah, alright. I was just wondering since I typically just looped through the table to find the position and then index from that, but felt that was redundant and wondered if there was a quicker way to find the position. Thanks for the answer! PreciseLogic 271 — 7y
Ad

Answer this question