Im trying to make an inventory system for my tower defense game and I made this function to find the tower in a dictionary:
type tower = {Name: string, ImageAsset: string, Rarity: string}
local function getTowerByKey(key: string): tower?
for _, rarity in pairs(towers) do
local tower = rarity[key]
if tower then return tower end
end
return nil
end
(I did it like this because the table looks something like this)
["Common"] = {
["CCTV-Man"] = {
["Name"] = "CCTV-Man",
["ImageAsset"] = "http://www.roblox.com/asset/?id=13749054780",
["Rarity"] = "Common"
},
["Speakerman"] = {
["Name"] = "Speakerman",
["ImageAsset"] = 'http://www.roblox.com/asset/?id=13749300689',
["Rarity"] = "Common"
},
["TV-Man"] = {
["Name"] = "TV-Man",
["ImageAsset"] = "http://www.roblox.com/asset/?id=13767180458",
["Rarity"] = "Common"
},
},
Anyways when I call the function, it returns nil but only when I do it with the players SelectedTowers but it works fine with the OwnedOnes, heres the code btw:
function updateItems()
print(playerData)
for i, key in pairs(playerData.OwnedTowers) do
local tower = getTowerByKey(key)
--find old button
local oldButton = inventoryFrame:FindFirstChild(tower.Name)
if oldButton then
oldButton:Destroy()
end
--creating new button
local newButton = template:Clone()
newButton.Name = tower.Name
newButton.Image = tower.ImageAsset
newButton.Parent = inventoryFrame
local towerfromRs = replicatedStorage.Towers:FindFirstChild(tower.Name)
newButton.LayoutOrder = (towerfromRs.Config.Price.Value) + 999999999
local status = getItemStatus(tower.Name)
if status == "Equipped" then
print(newButton.Name.." is equipped!")
else
print(newButton.Name.." is owned!")
end
newButton.Activated:Connect(function()
interactItem(tower.Name)
end)
end
for i, selectedKey in pairs(playerData.SelectedTowers) do
print(selectedKey)
local selectedTower = getTowerByKey(selectedKey)
print(selectedTower)
--find old button
local oldButton = inventoryFrame:FindFirstChild(selectedTower.Name)
if oldButton then
oldButton:Destroy()
end
--creating new button
local newButton = template:Clone()
newButton.Name = selectedTower.Name
newButton.Image = selectedTower.ImageAsset
newButton.Parent = inventoryFrame
local towerfromRs = replicatedStorage.Towers:FindFirstChild(selectedTower.Name)
newButton.LayoutOrder = (towerfromRs.Config.Price.Value)
local status = getItemStatus(selectedTower.Name)
if status == "Equipped" then
print(newButton.Name.." is equipped!")
else
print(newButton.Name.." is owned!")
end
newButton.Activated:Connect(function()
interactItem(selectedTower.Name)
end)
end
end
The variable “SelectedTower” returns nil. Any help is appreciated, thanks!