Attempting to get the closest value from a array for a small project.
I have tried two different methods, closest.Value and just .closest.
I get errors either way.
local HowMany = math.random(100,300)
local PlayerGuesses = {} --numbers get added here in-game
for i, currentNum in pairs(PlayerGuesses) do
local diff = math.abs(currentNum - HowMany)
if diff < closest then
closest = currentNum
end
end
Status.Value = "Winner : "..closest.Value
local HowMany = math.random(100,300)
local PlayerGuesses = {}
local closest = nil
local lowestDiff = math.huge
for i, currentNum in pairs(PlayerGuesses) do
local diff = math.abs(currentNum - HowMany)
if diff < lowestDiff then
lowestDiff = diff
closest = currentNum
end
end
Status.Value = "Winner : "..closest
I see, so closest is an object value. Replace local closest = 0 with local closest, and "Winner : "..tostring(closest) with "Winner : "..(closest and closest.Name) or "nobody won"
local PlayerGuesses = game.ReplicatedStorage.Events.Number:InvokeServer()
script.Parent.TextBox.FocusLost:Connect(function()
if script.Parent.TextBox.Text == not "" then
--x
else
local num = script.Parent.TextBox.Text
table.insert(PlayerGuesses, tostring(num))
print(PlayerGuesses)
end
end)
It works for me. Run this in the command bar. I also changed the values in the PlayerGuesses table to strings and it still works.
local HowMany = math.random(100,300)
local PlayerGuesses = {"100", "150", "200", "250"}
local closest = nil
local lowestDiff = math.huge
for i, currentNum in pairs(PlayerGuesses) do
local diff = math.abs(currentNum - HowMany)
if diff < lowestDiff then
lowestDiff = diff
closest = currentNum
end
end
print("HowMany = "..HowMany)
print("Closest = "..closest)
and this is what I changed it to and it still sets winner to nil.
local PlayerGuesses = {}
local closest
local lowestDiff = math.huge
for i, currentNum in pairs(PlayerGuesses) do
local diff = math.abs(currentNum - HowMany)
if diff < closest then
lowestDiff = diff
closest = currentNum
end
end
Status.Value = "Winner : "..tostring(closest)
You need to check if the closest value is nil and then if it is you will need to set it as something i just need to know what your goal is. What is the closest variable needed for?
I’m trying to make a game where there is a random amount of items set into a jar and then each players guesses and whoever is closest wins the round.