I need help with tables

If I have this, how do I get the name of two and value three, and how to determine the length (#) of one?

Btw what is the [“two”], called? It’s not a table, is it?

local one = {
["two"] = {"three", "four"}
}

string.len can be used to find the amount of characters in a string.

for i,v in pairs(tbl) do
print(i,v)
end

In this code, i is the index (two) and v is the value ({‘three’, ‘four’})

Thank you, but by length I meant like

local table = {1,2,3,4}
print(#table)

I meant the “#table” thing, I don’t know the name, sorry. I tried that with my table and it didn’t work

Not quite sure what you’re asking.

print(#one["two"])
local one = {
["two"] = {1,2,3,4},
["three"] = {a,b,c,d}
}

The length of one (#one) is 2, but that doesn’t work, how do I get the length of the table “one”

Oh, I see. Why do you need to do this? I can’t think of a single application where this would be helpful.

one = {
["two"] = {1,2,3,4},
}

local function GetTableName(tbl)
	for i,v in pairs(getfenv()) do
		if v == tbl then return i end;
	end
	return nil;
end

print(GetTableName(one));

This works, but your table must be a global variable, not local.

Dictionaries do not have a length because they are not in the array part of the table.
Dictionaries are parts of the table where the key is mapped onto the table instead of using an index that follows the order and count of an array. (The details of how this works gets complicated)
The # operator will only count how many elements are in the array part of a table.
If you want to count how many elements there are in total, try this (but it may be inaccurate when deleting elements):

local length = function(tbl)
    local count = 0
    for _ in next, tbl do
        count = count + 1
    end
    return count
end
1 Like

Thank you, that was what I needed. Also just a side question, do you know how I can make a for function going [“two”] and [“three”] (just the dictionaries), and then have a for function inside to go to the arrays of two and three?

You do just that…?

for key, data in next, tbl do
    for index, value in next, data do
        print(key, data, index, value)
    end
end