I am trying to construct a mathematical engine that can take a set of numbers written in chat by the player, and rearrange them in ascending order. To start, I am attempting to make a function which will return the lowest number in a table. Here is what I have so far;
local function Lowest(Set)
for i, v in pairs(Set) do
if i == 1 or Lowest > v then
Lowest = v
end
end
return Lowest
end
For some reason, when I plug in the set “4, 20, 5”, 20 is returned as the lowest value. It seems like the code does not recognize the fact that there is a 0 at the end. I’ve tried scouring the forums, and have not stumbled upon anyone having similar issues. I am quite new to this, so I must be missing something pretty obvious!
I think you didn’t define a variable “Lowest” in the function.
Here’s what I would write
local function GetLowestNumber(Set)
-- set a variable "Lowest" that will hold the lowest number
local Lowest = 0
-- for every thing in the set
for _, Value in pairs(Set) do
-- check if you need to replace the "Lowest" variable with the value in the set
if Lowest == 0 or Value < Lowest then
Lowest = Value
end
end
return Lowest
end
local function lowest(set)
--Assuming all entries in set are numbers
local current = nil
for i, v in ipairs(set) do
if not current then
current = v
continue
end
current = math.min(current, v)
end
return current or error(“Empty Table”)
end
Before urun the loop check if the indices are greater than 1, else do your algorithm checking the former to the current. The chicken or the egg solution here is to put some ridiculously high number as the first one
Well, setting current to nil first, then looping through the set. If current is nil, which will run on the first iteration since no changes were made, we set our current to the current value, then continue to the next iteration. then on the next iteration we check the lowest value between current lowest, and the current value in the set. Math.min just returns the lowest number between the two. It continues on until the last iteration.
local function lowest(set)
--Assuming all entries in set are numbers
local current = nil
for i, v in ipairs(set) do
if not current then
current = v
continue
end
current = math.min(current, v)
end
return current or error(“Empty Table”)
end
added indentation to make the solution more readable