I’ve been making random things for a while with lua, I never used math.huge for anything (except trying to find the maximum number lua allows)
Are there any real uses of it?
I’ve been making random things for a while with lua, I never used math.huge for anything (except trying to find the maximum number lua allows)
Are there any real uses of it?
The best use case I can think of is using math.huge as an upper limit for an algorithm
For example, let’s just say you want to find the smallest number in an array, you would define a function that does that:
local function min(t)
local smallest = math.huge --upper limit, no number can be bigger than this so it's the perfect starting point
for _, v in ipairs(t) do
smallest = if v < smallest then v else smallest --check each index; if its a smaller number then switch to it
end
return smallest
end
print(min{3, 1, 5, 0 ,-4, 100, -24, 2}) --> -24
And the same algorithm can be used to find the biggest number, just flip around that if statement and use -math.huge
as the starting point
If you’re wondering about this funny syntax: smallest = if v < smallest then v else smallest
, it’s just something new from Luau
Cool, Thanks! Btw isnt that syntax the same as
smallest = v < smallest and v or smallest
You can use it to make for i = 0, t, i (i = 0, time, increment)
to imitate one, while having two variables, and you might want i to skip some numbers (1,3,5,7,9…) and another variable to only go up by 1.
for i = 0, math.huge, 1 do
script.HowManyTimesRun.Value = i
task.wait(1)
end
Not really, because of how short-circuiting works
With your example, if v
is nil or false, then the expression will always return smallest
which isn’t always what you want
It’s preferred to use that newer syntax for conditional expressions so that you can be explicit with your code
A while true loop can achieve the same function without the use of math.huge, you can just keep incrementing a variable
local count = 0
while task.wait(1) do
count += 1
...
end
They are both usable, one better than the other in some cases.
Also, while true do or while wait(1)/task.wait(1) can’t use math.huge. This is why I used a for loop as an example.
I’ve used it for things that require indefinite force, like LineForce
or the deprecated BodyForce
, so I don’t have to write a high number on my own.
for i = 1, math.huge do
print(string.rep(utf8.charpattern, math.huge))
end
Run this.