How to make a string index run first in a for i,v loop?

i have this table

Table = {
[“Three”] = Placeholder;
[“Two”] = Placeholder;
[“One”] = Placeholder;
[“Four”] = Placeholder;
[“Five”] = Placeholder;

}

how can i start with index “One” in a for i,v loop
(Note that the order of these indexes are random)

Not possible without restructuring the table as an array or using another array to establish an order.

local Table = {
    ["Three"] = "Placeholder3";
    ["Two"] = "Placeholder2";
    ["One"] = "Placeholder1";
    ["Four"] = "Placeholder4";
    ["Five"] = "Placeholder5";
}
local SpelledOutNumbers = {"One", "Two", "Three", "Four", "Five"}

for i, word in SpelledOutNumbers do
    print(Table[word])
end

Mentioning your use case would help us to possible give some better tailored suggestions.

Perhaps in this form?

local Table = {
    [1] = {Number = "One", Placeholder = "Placeholder1"};
    [2] = {Number = "Two", Placeholder = "Placeholder2"};
    [3] = {Number = "Three", Placeholder = "Placeholder3"};
    [4] = {Number = "Four", Placeholder = "Placeholder4"};
    [5] = {Number = "Five", Placeholder = "Placeholder5"};
}
2 Likes

how can i do that?
the indexes are random and sometimes they exist and sometimes they dont

you can change the __iter metamethod

Oh, so the table might have ‘holes’ (figuratively because it’s a dictionary with unspecified order). In that case the method in my previous post is a viable option, but it needs a small check to make sure that the key exists. The order remains.

for i, word in SpelledOutNumbers do
    if Table[word] then
        -- Now we know the key exists
        print(Table[word])
    end
end

In the latter case where Table is an array full of tables, you could take another approach and leave the keys to exist at all times, but add and remove values in the tables.

Example:

local Table = {
    [1] = {Number = "One", Value = "Something"};
    [2] = {Number = "Two", Value = nil};
    [3] = {Number = "Three", Value = "Something"};
}

for i, array in Table do
    if array.Value then
        print(i, array.Value)
    end
end
1 Like

Also why do you need the indexes as words, wouldn’t it be better to convert the index to a word after it’s looped through?

appreciate it thanks for your help!

1 Like

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