donzee529
(Donzee)
October 13, 2020, 3:01pm
#1
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?
sjr04
(uep)
October 13, 2020, 3:02pm
#2
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)
donzee529
(Donzee)
October 13, 2020, 3:02pm
#3
Is my current dictionary correct?
Cool, but how do you remove one from it?
sjr04
(uep)
October 13, 2020, 3:03pm
#5
Yeah yours is fine, it’s an array of dictionaries, so iterating over it should be easy
sjr04
(uep)
October 13, 2020, 3:03pm
#6
table.remove(food, index_of_food_to_remove)
Okay, thank you very much for the fast reply.
donzee529
(Donzee)
October 13, 2020, 3:22pm
#8
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!
un1ND3X
(ice)
October 13, 2020, 6:18pm
#9
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