Bkbbkk Kkbbkb
Bkbbkk Kkbbkb

Reputation: 1

Lua nested table get all elements from table if element in table is set to True

Fruits = { apple = { ordered = true, amount = 10 }}

i have several different kinds of fruits in this table and i need to output everything where ordered=true to make it look like this:

apple ordered: true | apple amount: 10

Made it like this

for a,b in pairs(Fruits) do
   for c,d in pairs(b) do
      if (d == true) then
         print(a..” ordered: ”..tostring(d)..” | “..a..” amount: “..tostring(d)..”)
      end
   end
end

but the output is this

apple ordered: true | apple amount: true

Upvotes: 0

Views: 70

Answers (1)

Luatic
Luatic

Reputation: 11191

The problem with your code is that you're looping over the "properties" of each fruit. Thus you have c = "ordered" and d = true inside the loop. Printing d twice will lead to the output you have described. Here's the fixed code:

for name, props in pairs(Fruits) do
    if props.ordered then
        print(name .. " ordered: true | amount: " .. props.amount)
    end
end

Upvotes: 1

Related Questions