How to get the length/amount of items in a subtable?

How could i get the amount of items in a table inside another table ?

Example :

local table_ = {   -- < Not this one
      value1 = 1,
       somestring = "w",
      myitems1 = {  -- I want to get the amount of items in this table
          ["ThisTable"] = { -- << In this one too, but separated
                item1 = 1
                item2 = 2
          }
      }
}
3 Likes

# will always return 0 when you attempt to use it to get the length of a dictionary. The tables that you provided are all dictionaries, so they don’t necessarily have a clear order or length. You could convert myitems1 into an array, or alternatively just use a function to count the # of top-level values:

local someDictionary = {
	TestValue = 1,
	Nested = {
		Value = 2,
	},
}

local function getDictionaryLen(t)
	local k = 0
	for _, _ in t do
		k += 1
	end
	return k
end

print(getDictionaryLen(someDictionary)) -- prints 2
5 Likes

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.