Search code examples
lualua-table

LUA - Is possible to get values of an index in a multidimensional table?


It is possible to get/return multiple values of an index in a multidimensional array/table? I have tried lots of methods but none seem to work or at least IDK how to implement them since I'm new to Lua.

This is what I have done or got so far, my table looks like this:

data = {
   ["oranges"] = {
      ["price"] = {
         "0.23",
      },
      ["location"] = {
         ["nearest"] = {
            "Russia",
            "United States",
         },
         ["farthest"] = {
            "Brazil",
            "Australia",
         },
      },
   },
   -- More...
}

What I want from that is all values from let's say ["nearest"] The function I'm working with is a mess but well:

function getNearestLocation(data)
   for k, v in pairs(data) do
      if v == "oranges"
      then
         -- Whatever I do here can't get it to work.
         for data, subdata in pairs({v}) do
            if subdata == "location"
            then
               return subdata["nearest"]
            end
         end
      end
   end
end

It is possible then to get {"Russia","United States"} for example. Thanks in advance.


Solution

  • The table you seek is data["orange"]["location"]["nearest"].

    If you need a function, use

    function getNearestLocation(data)
       return data["orange"]["location"]["nearest"]
    end