Print does not return table values

Asked

Viewed 107 times

3

pokecatches = {
["Bulbasaur"] = {chance = 150, corpse = 5969},
["Ivysaur"] = {chance = 275, corpse = 5982},
["Venusaur"] = {chance = 400, corpse = 5962},
}
print(table.maxn(pokecatches))
corpses = {}
for x=1, table.maxn(pokecatches) do
table.insert(corpses, pokecatches[x].corpse)
end
print(table.concat(corpses, ","))
io.read()

This snippet should add the Corpse value to the Corpses table, but it won’t, print(table.man(pokecatches)) returns 0. Anyone knows why?

1 answer

4


The problem is you want to iterate on one set as if it were a simple table.

One possibility to adjust the code is to restructure the data as a table, to iterate by numerical index (pokecatches[x]):

pokecatches = {
   { name = "Bulbasaur", chance = 150, corpse = 5969},
   { name = "Ivysaur"  , chance = 275, corpse = 5982},
   { name = "Venusaur" , chance = 400, corpse = 5962},
}
print(table.maxn(pokecatches))
corpses = {}
for x=1, table.maxn(pokecatches) do
   table.insert(corpses, pokecatches[x].corpse)
end
print(table.concat(corpses, ","))

The Outram to maintain the use of sets, is iterate with for .. in to obtain the key and value data with pair:

pokecatches = {
   ["Bulbasaur"] = {chance = 150, corpse = 5969},
   ["Ivysaur"] = {chance = 275, corpse = 5982},
   ["Venusaur"] = {chance = 400, corpse = 5962},
}

corpses = {}
for name, data in pairs(pokecatches) do
   table.insert(corpses, data.corpse)
end
print(table.concat(corpses, ","))

See the two working on IDEONE

  • I found it more feasible to use the second option, since the table has more than 300 elements. Thanks.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.