3 Replies Latest reply on Apr 25, 2012 9:52 AM by johnrellis

    Table of Tables


      How in the world do I easily access keys in a table of tables? For example, LrHttp.post returns the header response from an http request in a mixed table.  Here's the code I'm using just to get access to a header value. Is this the right way to do it?


      local strTarget = 'header_to_find'

      local answer


      for k,v in pairs(headers) do


           if tostring(v):match("(table).*") == "table" then --this tells me the element is a table


             if v["field"] == strTarget then


                     answer = v["value"]





      end -- for k,v in pairs(headers) do

        • 1. Re: Table of Tables
          johnrellis Most Valuable Participant

          I think your code is correct, but it's more verbose than it needs to be.  According to the documentation, the headers returned by LrHttp.post is actually an array of tables (an array is a table whose keys are sequential integers starting at 1), and each of the elments of an array is a table, so you don't need to test for the type of the element.  Thus, a more concise version would be:


          local strTarget = "header_to_find"
          local answer
          for i, header in ipairs (header) do
              if header.field == strTarget then
                  answer = header.value
          • 2. Re: Table of Tables
            optimator999 Level 1

            Hi John,


            The issue I ran into is that it's not just a table of tables, but includes field names such as status. This makes it easy to check the status of the http call, but I think it means I have to loop through the return table, checking to see if each element is a table and then to see what the key is and then assign the value if I like the key.

            • 3. Re: Table of Tables
              johnrellis Most Valuable Participant

              The ipairs() iterator in the code fragment above will skip over entries in the top-level table whose keys are not integers (e.g. "status").  The headers are a common Lua idiom, adding a non-integer key to an array (a table where the keys are integers).


              Also, though you don't need it in this case, here's the more concise way to test whether a value "v" is a table:


              type (v) == "table"

              1 person found this helpful