Hey! I stuck with a game for once! This time around, I’m implementing a highscore feature. However, I don’t know how to get a single value from a table using a name.
Here’s the snippet. The table.find part appears to be returning nil, as the print says highscore = nil.
for _,maptomoveback in pairs(workspace.Map:GetChildren()) do
maptomoveback.Parent = game:GetService("ReplicatedStorage").Maps
local mapname = maptomoveback.Name
print(mapname)
local highscore = table.find(highscores, mapname)
print(highscore)
if game.Workspace.BoxesDelivered > highscore.Value then
highscores.Value = game.Workspace.BoxesDelivered
high = true
else
high = false
end
workspace.failGUIevent:FireAllClients(mapname, high)
end
Is the any more optimizations I can make, and how do I search a table using a string?
I’m assuming you’re using a dictionary here. If so realistically you should be able to just do this:
if game.Workspace.BoxesDelivered > highscores[mapname]["Value"] then
Having said that I’m not completely sure that would work either if table.find doesn’t. table.find takes a haystack and needle parameter, and if the needle isn’t in the haystack it returns nil, suggesting it’s most likely an issue with your dictionary or the way you’re indexing.
It doesn’t appear to work this way either. The issue is that the table.find is returning nil, and so does your solution. I don’t know how to look for a value based on a name in a folder, so this was my best guestimate.
Could you provide the full code and hierarchy of highscores? As I mentioned if table.find is returning nil then there is an issue with the table you’re using. You could actually do something like:
for _,v in pairs(highscores) do
print(v.Name)
if v.Name == mapname then
print(mapname.." found!")
end
end
This should demonstrate my point, if not then there’s something very weird going on.
Edit:
I missed that you’re using a folder of instances. That still doesn’t explain why my original suggestion of highscores[mapname].Value doesn’t work though. On a side note, since you’re just using instances you should be able to just do:
highscores:FindFirstChild(mapname)
If not there’s still a problem with your hierarchy.
GetChildren() returns an array of instances. You are looking for a string (the name) when the list is not strings. You could fix this by just table.find(highscores, maptomoveback)
Also you might be interested in table.sort:
If you wanted to sort your list you could do something like this:
-- sort scores from high to low
table.sort(highscores,function(score1,score2) return score1.Value > score2.Value end)
for place,score in ipairs(highscores) do print(place,score.Name,score.Value) end
-- sort scores from low to high
table.sort(highscores,function(score1,score2) return score1.Value < score2.Value end)
for place,score in ipairs(highscores) do print(place,score.Name,score.Value) end