I’m storing functions in a dictionary but when I use table.find to try and find them it’s always saying nil. I searched on the forum but just didn’t find any answers to my issue. Sorry if I searched for the wrong things or something.
local function PunchAttack(Player, EnemyToUse)
print("Player has punched that idiot enemy!")
local EnemyHumanoid = EnemyToUse:FindFirstChild("Humanoid")
EnemyHumanoid:TakeDamage(3)
wait(3)
end
local function PassAction(Player, EnemyToUse)
print("Player passed turn!")
end
----------------------------------------------
local StringKeys = { -- NEED HELP IN THE PRINT STATEMENTS HERE THEY RETURN NIL
["Pass"] = PassAction,
["Punch"] = PunchAttack
}
print(table.find(StringKeys, "Pass"))
Yes, this is because a dictionary is not a table and does not act like a table. Think of it as a list,
local myList = {"Apple", "Banana", "Orange"}
print(myList[2]) --> "Banana"
In a list, each item is indexed by a number correlating to it’s position in the list. A dictionary is very similar, but instead of indexing with increasing numbers, you can set the index (key) to just about anything you want, in this case Strings. Therefore, to grab an item from a dictionary, you want to do what you do with a list, and search for the specific key.
local myDictionary = {
["Key1"] = "Apple";
["Monkey"] = "Banana";
[Enum.KeyCode.LeftShift] = "Orange"; -- these keys can be anything!
}
print(myDictionary["Monkey"]) -- > "Banana"
So for your case, to get the item under key “Pass”, you would do StringKeys["Pass"]
Hmm, I still recieved an odd result when using table.find to find an item in the dictionary.
local StringKeys = {
["Pass"] = "Statement1",
["Punch"] = "Statement2"
}
print(table.find(StringKeys, "Pass")) -- Returns nil even though Pass is in the dictionary
Oh okay, it was hard to understand since the way you were phrasing it made me think that what you were saying would allow me to use table.find on a dictionary. I’ve never really encountered a scenario where I needed to use table.find to find something in a dictionary since i normally just check if I can index the thing i’m trying to find and see if it’s nil. What I’ve done for my battle system to check if the string key provided by the client response after selecting an action is to just index it and check if it’s nil. Thanks a lot and now i’ll know that table.find doesn’t work for dictionaries.