How to get the name of a table

I’m trying to get the name of a table. However, it isn’t working.
I’ve looked at several posts but they haven’t helped me.
(in the below post, I’m trying to set an instance’s name to the name of the table)

local metatable = {
	["Apple"] = {
		["Amount"] = true
	},
	["Orange"] = {
		["Amount"] = true
	},
}

for _, val in pairs(metatable) do
	local bool = Instance.new("BoolValue", script)
	bool.Name = tostring(val)
	bool.Value = val["Amount"]
end

It sets the name to table: 0x868756d68e4cafc5

This was a test script used to check if my issue persisted.

1 Like

I may be incorrect but is the value _ not the name of the name of the dictionary (for example apple would be _ = apple)

There’s no name of a table. If you want the Apple and Orange, use the _ value of the for loop. You’d change that to i or fruit or something though.

Could you give a script example of so? I don’t understand fully.

for fruit, val in pairs(metatable) do
	local bool = Instance.new("BoolValue", script)
	bool.Name = fruit
	bool.Value = val.Amount
end
2 Likes

Well it would be the same then what you have set up currently but rather then having the boolen name being set as “val” you would just set it as “_” but like what @bluebxrrybot said I would recommend changing it to something such as fruit.

Example:

local metatable = {
	["Apple"] = {
		["Amount"] = true
	},
	["Orange"] = {
		["Amount"] = true
	},
}

for fruit, val in pairs(metatable) do
	local bool = Instance.new("BoolValue", script)
	bool.Name = fruit
	bool.Value = val["Amount"]
end
1 Like

It worked. Just one more question: I thought the first argument returned the index number of the value…?

It does with a normal table but it is due to you having a dictionary within the table that you get the key rather then a number (or at least I think that is why).

1 Like

The i in for i, v in pairs is the key of the table. If it’s a list, it is a number. If it’s a dictionary, it’s whatever the key is.

local list = {"a","b","c","d","e"}
local data = {
    Test = true,
}
for i, v in pairs(list) do
    print(i) --> 1, 2, 3, 4...
end
for i, v in pairs(data) do
    print(i) --> Test
end
3 Likes

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