0Enum
(0Enum)
August 17, 2021, 3:32pm
#1
I’m trying to get the largest number out of a table. It is not accepting the table and will only accept numbers entered.
This is my code:
local numberTable = {1,3,7,5,0}
local function max()
print(math.max(4,6,8,5,3,6,8))
end
max()
I want to change the numbers with the table so I don’t type the numbers each time.
caviarbro
(caviarbro)
August 17, 2021, 3:34pm
#2
local tab = {1,2,3,4,5}
table.sort(tab,function(a,b)
if a > b then
return a
end
end)
print(tab[table.getn(tab)]) -- lowest number
print(tab[1]) -- highest number
--// or
print(math.max(unpack(tab)))
3 Likes
kndn_v
(kanden)
August 17, 2021, 3:35pm
#3
Have you looked into table.sort?
local t = {1,5,2,8,1}
table.sort(t)
print(t) -- 1,1,2,5,8
0Enum
(0Enum)
August 17, 2021, 3:39pm
#4
I wanted it to get the highest number not the numbers in ascending order.
kndn_v
(kanden)
August 17, 2021, 3:41pm
#5
Then use t[#t]
as your result. Alternatively, you can sort them backwards.
local t = {1,5,2,8,1}
--method 1
table.sort(t)
print(t[#t]) -- 8
--method 2
table.sort(t, function(a,b)
return a>b
end)
print(t[1]) -- 8