Tomáš Zato
Tomáš Zato

Reputation: 53129

Loop over big Lua table literal using ipairs doesn't do anything

I come to Lua from Javascript, but there are some significant differences that cause me to do stupid things. I defined a table literal to hold some static data:

ObjectTypeDefs = {
  mailbox={
    time=40,
    yield={{name="Base.Plank"}, {name="Base.Newspaper"}, {name="Base.ScrapMetal"}},
    tools={{"Base.AxeStone", "Base.Axe"}},
    cheat=false,
    displayName="Mailbox"
  },
  laundry={
    time=300,
    yield={{name="Radio.ElectricWire"}, {name="Base.ScrapMetal"}},
    exp={electrical=3},
    tools={"Base.Screwdriver", "Base.KitchenKnife"},
    cheat=false,
    displayName="Laundry machine"
  },
  wood_chair={ ... and so on ...}

  ... more items here ...
}

Yo can see the tools sub-key in every entry. That defines some game tools required to perform some operation. I want to assign some validator function to all tools subkeys. I tried to do this:

  print("Initializing object definitions: ");
  -- Here, callbacks for definitions are assigned
  for i,v in ipairs(ObjectTypeDefs) do
    print("Defining checkItems callback for "..i..".");
    v.tools.checkItems = ... some closure here ...;
  end

But all output I get is:

Initializing object definitions:

The for loop doesn't even start. What's wrong with it? Here's runnable sample: http://ideone.com/QqYU04

Upvotes: 1

Views: 1590

Answers (3)

Alexander Gladysh
Alexander Gladysh

Reputation: 41393

You have to use pairs to iterate over the hash part of a table. ipairs are for iteration over a numeric part of a table (and is sometimes better replaced with numeric for).

This is not related to the question, but watch over your globals too. Are you sure that ObjectTypeDefs has to be a global variable?

Upvotes: 3

Piglet
Piglet

Reputation: 28950

ipairs iterates over integer indices starting from yourTable[1] and ending at the first table element that is nil.

You have to use pairs or next (which is used by pairs internally). But keep in mind that output order is arbitrary.

for k,v in pairs(yourTable) do
  ...
end

or

for k,v in next, yourTable do
  ...
end

http://www.lua.org/pil/7.3.html

Upvotes: 3

hjpotter92
hjpotter92

Reputation: 80639

You're using ipairs which iterates only over integer indices. You should instead use pairs.

Upvotes: 3

Related Questions