Help with tables

Hey, I have a question related to table keys
I am trying to make the script give the name and value of key if I enter the first letter of the key

Players = {
Apples = 5,
Oranges = 10,
Grapes = 15
}

if I press G, I want the script to print Grapes = 15 in the output.
Or if I press a letter, I want the scrip to print all the keys and values of all keys starting from that letter.

If I am understanding correctly you want to print out the values each thing in the table?

local MyTable = {
   Apples = 5;
   Oranges = 10;
   Grapes = 15;
}

for _, Value in pairs(MyTable) do
    print(Value)
end

you can get the key to string by doing Input.KeyCode.Name the loop through the table with a for loop, use string.sub to get the first letter and if it’s the same break so it doesn’t continue looping

No, for example if I press A, I want to print Apples = 5, Oranges = 10 is I press O and so on…

1 Like

how to get the first letter ?

local firstValue
for indexName:string, value:number in players do
local FirstLetter = string.sub(indexName,1,1)
if string.upper(FirstLetter) == inputName then
firstValue = indexName
break
end
end

sorry if there’s any errors i wrote this on mobile

2 Likes

Im not good at manipulating strings, but to get a whole filter list, I would try to populate a new filterTable to make it easier at least for me:

local Fruits = {
	Apples = 5,
	Oranges = 10,
	Grapes = 15,
	Abanana = 20
}

local FilterTable = {}

for n, v in pairs(Fruits) do
	if not FilterTable[string.sub(n, 1, 1)] then
		FilterTable[string.sub(n, 1, 1)] = {n}
	else
		table.insert(FilterTable[string.sub(n, 1, 1)], n)
	end
end

-- Print whole Filters
warn(FilterTable)

-- Print Filters which starts with A
print(FilterTable["A"])

-- Find the values of Filters that start with A
for _, f in pairs(FilterTable["A"]) do
	warn(f, ":", Fruits[f])
end
1 Like

Yep that works :slight_smile:

1 Like

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