Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

Can you do absolute value in lua?

Asked by 9 years ago

If you do print(|-3|) would it print 3? I tried this once and it didn't work, but I still think there is a way to find absolute value. I want it to be simple and not like:

local number = {-4, 4, 5, -98}

for _, num in pairs(number) do
    if num > 0 then
    num = num*-1
    print(num)
    else
    print(num)
end

I also want to know if you can do factorial in lua: print(3!) should print 6, unless I've done it wrong(that would be embarrassing.) This is how you could do it but it's too long.

local number = {3, 5, 7}

for _,num in pairs(number) do
    if num == 0 then
    print(1)
    elseif num < 0 then
    repeat
        bleh = -1
        num = num*num+bleh
        bleh = bleh-1
    until num-bleh = 1
    print(num)
    elseif num > 0 then
    repeat
        bleh = 1
        num = num*num-bleh
        bleh = bleh+1
    until num+bleh = -1
    print(num)
    end
    end
end

Thanks in advance! BTW: I know these scripts don't work, I made them in under a min. Expect bugs and me spelling things wrong.

0
Wow, this is a legit question, if you don't know math, that's no excuse for thumbing down. EzraNehemiah_TF2 3552 — 9y

1 answer

Log in to vote
0
Answered by
adark 5487 Badge of Merit Moderation Voter Community Moderator
9 years ago

The abs function of the math library does absolute values. As for factorials, you have to program that yourself:

function factorial(num)
    num = math.abs(num)     --Factorial only works for positive numbers.
    num = math.floor(num + .5) --Factorial only works for integers.
    local result = num
    while num > 0 do
        num = num - 1
        result = result*num
    end

    return result
end
0
Thank you! EzraNehemiah_TF2 3552 — 9y
0
Oh It's like a joke, abs sounds like absolute and in the parameters is a number VALUE. Absolute Value. EzraNehemiah_TF2 3552 — 9y
0
I have no idea what you mean by that. `abs` is simply shorthand for `absolute` adark 5487 — 9y
0
nvm, I just see everything as puns. Like in the () there is a number VALUE so it's absolute VALUE. EzraNehemiah_TF2 3552 — 9y
Ad

Answer this question