local highestValue = 0
local highestItem
for item, cost in ipairs(Items) do
if cost > highestValue and cost <= money then
highestValue = cost
highestItem = item
end
end
local highestValue = 3750000
local highestItem
for item, cost in ipairs(Items) do
if cost > highestValue and cost <= Player:WaitForChild("leaderstats").Cash then
highestValue = cost
highestItem = item
print(highestItem)
end
end
It isn’t printing anything so I think that it hasn’t found any items
local function GetHighestFromNumber(table,number)
local Highest = 0
for _,v in pairs(table) do
if Highest < v and number >= v then Highest = v end
end
return Highest
end
if u want to return index to then
local function GetHighestFromNumber(table,number)
local Highest,index = 0,0
for i,v in pairs(table) do
if Highest < v and number >= v then Highest = v index = i end
end
return Highest, index
end
local function countDictionary(dictionary)
local count = 0
for key, value in next, dictionary do
count += 1
if not next(dictionary, key) then
return count
end
end
end
Not what you asked for but here’s a dictionary count function.
local function convertToArray(dictionary)
local array = {}
for key, value in next, dictionary do
table.insert(array, {key, value})
end
return array
end
local function sortDictionary(dictionary)
local array = convertToArray(dictionary)
table.sort(array, function(left, right)
if left[2] > right[2] then
return left
end
end)
return array
end
local dict = sortDictionary({["a"] = 1, ["b"] = 2, ["c"] = 3})
for _, data in ipairs(dict) do
print(data[1], data[2])
end
--[[
output:
c 3
b 2
a 1
]]
and here’s a dictionary sorting function which doesn’t just return the item/entry with the largest value but it returns all items/entries in descending order of their values (largest to smallest).
One issue with this is it won’t be able to sort negative numbers as the variable “Highest” starts at 0.
local function getLargestValue(dictionary)
local index, largestValue = nil, -math.huge
for key, value in next, dictionary do
if value > largestValue then
largestValue = value
index = key
end
end
return index, largestValue
end
local function getSmallestValue(dictionary)
local index, smallestValue = nil, math.huge
for key, value in next, dictionary do
if value < smallestValue then
smallestValue = value
index = key
end
end
return index, smallestValue
end
local dict = {["a"] = 1, ["b"] = 2, ["c"] = 3}
local index, largestValue = getLargestValue(dict)
print(index, largestValue) --a 3
local index, smallestValue = getSmallestValue(dict)
print(index, smallestValue) --c 1
Here we compare against -math.huge/math.huge to circumvent that issue.