Multidimensional Tables

So in my output all I am getting is the first “ScriptRunning” and 0 from the last line which is suppose to be the length of the table. It’s almost like the the values are hidden and can only be accessed when directly called IE: MasterTable["Meta"]["A"]
What am I doing wrong here… Cant a guy just iterate through a table of tables in peace.

print("ScriptRunning")

MasterTable = {
	Meta = {
		A = 2;
		B = 4;
		C = 2;
	};
}


for z,v in ipairs(MasterTable) do
	print(tostring(z).." is the key")
	print(tostring(v).. " is the value")
end

for i = 1,#MasterTable do
	print(MasterTable[i])
end


print(#MasterTable)
1 Like

What you’ve created here is a Dictionary. Dictionaries are different from Arrays in that they can have customized keys instead of integer keys. The downsides of dictionaries are that you cannot easily get the length of the dictionary, and you cannot get a consistent “order” when iterating through a dictionary.

MasterTable = {
	Meta = {
		A = 2;
		B = 4;
		C = 2;
	};
}


for Key,Value in pairs(MasterTable["Meta"]) do -- To iterate through key/value pairs
    print(Key, Value)
end

local Size = 0
for Key,Value in pairs(MasterTable["Meta"]) do -- To get dictionary size
    Size = Size + 1
end
print(Size)
3 Likes

You are trying to iterate over the integer keys of a table which is not an array. You have a dictionary, so in order to index it you will need to loop with pairs or next.

for i,v in next,MasterTable do
print(i,v)
end
– this will print “Meta” and then tableX

Also note that you cannot get the length of the dictionary part of a table. For that, you will also need to loop over the contents and add +1 for each key/value pair to a variable outside of the loop.

3 Likes