0

I am trying to learn how to print strings from a value in a table. For example.

TestTable = { "Apples" = 0, "Oranges" = 1, "Grapes" = 1, "Bananas" = 0}

for i=1, #TestTable do
   if TestTable[i] == 1 then
      print(TestTable[i]) --> Oranges Grapes
   end
end

Not sure if that made sense, but I want to print all the strings with the 1 value.

1
  • 3
    BTW, your table constructor is incorrect, change "Apples" = 0 to either Apples = 0 or ["Apples"] = 0. Commented Feb 6, 2015 at 7:14

1 Answer 1

2

Unless the __len metamethod is defined, the # operator can only be used on a sequence, but TestTable is not one.

You can use pairs to iterate the table:

TestTable = { Apples = 0, Oranges = 1, Grapes = 1, Bananas = 0}

for k, v in pairs(TestTable) do
    if v == 1 then
        print(k)
    end
end
Sign up to request clarification or add additional context in comments.

2 Comments

It works. I am curious why "apples", "oranges", etc don't need quotes?
@BenjaminCondrea It's syntactic sugar. See PiL.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.