How to get the length of a table with negative values?

  1. What do you want to achieve? Keep it simple and clear!
    I want to find the minimum and maximum values of a table with negative, positive, and zero indexes. Using #table only starts at 1. Is it possible to get this with a built-in function, or do I need to write my own function to do this?

  2. What solutions have you tried so far? Did you look for solutions on the Developer Hub?
    I have tried using # and using a for loop with ipairs. Both methods start counting at 1. I have researched, but couldn’t find anything related to this.

I would do a for loop with pairs instead of ipairs.

When you have keys that are not in order, or do not start at 1, you have a dictionary. Here’s a simple function that returns the total number of values inside of a dictionary.

local function GetLengthOfDictionary(t)
    local length = 0
    for _ in pairs(t) do
        length = length + 1
    end
    return length
end


local testDictionary = {
    [-52] = "a";
    ["foo"] = "b";
    ["test"] = "c";
    [123712] = "d";
}
print(GetLengthOfDictionary(testDictionary)) -- 4