Dictionary Help

I am making a game with multiple foods. How can I make a dictionary like this:

food = {
{name = "apple", type = "fruit"}, {name = "pear", type = "fruit"}
}

How can I do it that it will actually work, how can I loop through each food, to get its name and type, and how can I add food to the dictionary?

To iterate over it

for _, food in ipairs(foods) do
    -- use food.name, food.type
end

To insert to it

table.insert(food, new_food)

Is my current dictionary correct?

Cool, but how do you remove one from it?

Yeah yours is fine, it’s an array of dictionaries, so iterating over it should be easy

table.remove(food, index_of_food_to_remove)

Okay, thank you very much for the fast reply. :slight_smile:

I made a new table for testing that looks like this:

{name = "system", message = "Thank you for signing up!"}

That table is saved to a datastore like this:

msgs = {
{name = "system", message = "Thank you for signing up!"}
}

When I do:

for _,v in ipairs(accdata.msgs) do
print("got one")
end

Nothing prints. Help!

Nothing prints because you didn’t write code to print anything at all other than “got one”.

But assuming accdata.msgs is the table you’re talking about, go over every value and print each one.

for _, v in ipairs(tab) do
    print(v.name, v.message)
end

It is not printing anything because you are creating a table inside a table and therefore you need to iterate through both of them.

local msgs = {
{name = "system", message = "Thank you for signing up!"}
}

for _, tab in pairs(msgs) do
     print("Iterating through first table.")
     
     for name, message in pairs(tab) do
         print(name, message)
     end
end

Alternatively, you could just do:

local msgs = {
{name = "system", message = "Thank you for signing up!"}
}

for _, tab in pairs(msgs) do
     print(tab["name"], tab["message"])
end
1 Like