Question

Backpack = {Potion = 'backpack',Stack = 'bag',Loot = 'derp', Gold = 'random'}

Backpack[1] ~= 'backpack' -- nope

As you guys can see, I cannot call Backpack[1] since its not a numeral table, how would I generate a table after the construction of Backpack, consisting only of it's values? for example:

Table_to_be_Constructed = {Value of Potion,Value of Stack,Value of Loot,Value of Gold} -- this is what i need

It seems simple but I couldn't find a way to do it.

I need it this way because i will run a numeric loop on Table_to_be_Constructed[i]

Was it helpful?

Solution

To iterate over all the key-value pairs in a table, use the pairs function:

local Table_to_be_Constructed = {}
for key, value in pairs(Backpack) do
    table.insert(Table_to_be_Constructed, value)
end

Note: the iteration order is not defined. So, you might want to sort Table_to_be_Constructed afterwards.

By convention, the variable name _ is used to indicate a variable who's value won't be used. So, since you want only the values in the tables, you might write the loop this way instead:

for _, value in pairs(Backpack) do

For the updated question

Backpack has no order (The order in the constructor statement is not preserved.) If you want to add an order to its values when constructing Table_to_be_Constructed, you can do it directly like this:

local Table_to_be_Constructed = {
    Backpack.Potion, 
    Backpack.Stack, 
    Backpack.Loot, 
    Backpack.Gold
}

Or indirectly like this:

local items = { 'Potion', 'Stack', 'Loot', 'Gold' }
local Table_to_be_Constructed = {}
for i=1, #items do
    Table_to_be_Constructed[i] = Backpack[items[i]]    
end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top