Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
COMMUNITY QUESTION

Needing help with printing a string from a table in a table (?)

local example = {
	["Example"] = {
		["ex1"] = "a",
		["ex2"] = "b",
		["ex3"] = "c",
		["ex4"] = "d",
	}
}

for _,btns in pairs(script.Parent:GetChildren()) do
	if btns:IsA("ImageButton") then
		btns.MouseButton1Click:Connect(function()
			if table.find(example ,btns.Name) then --stops working here
				local info = table.find(example ,btns.Name)
				
				print(info.1) 
			end
		end)
	end
end

2 answers

use the key, not the index.

print(info.1) -- which should actually be info[1]

should be

print(info["ex1"])
local example = {
    ["Example"] = {
        ["ex1"] = "a",
        ["ex2"] = "b",
        ["ex3"] = "c",
        ["ex4"] = "d",
    }
}

Tables are split into two components: the array component, and the hash-table (dictionary) component. Arrays are defined by ascending numerical indices.

table.find will perform a search through the array component by ascending through its indices, however, as example is entirely a dictionary, that search will quickly cease. The key-value pairs you desire are also not directly within example.

The correct code is:

local info = example.Example[btn.Name]
if info then
	-- Use 'info' ...
end

The information at example.Example[btn.Name] is also a string, so writing info.1 does not make sense. The syntax itself is illegal.

It seems like you need to read up on tables.

This discussion is preserved as it was. New answers, comments, and votes are closed.