Math: Get Just the Sign

Questions about the LÖVE API, installing LÖVE and other support related questions go here.
Forum rules
Before you make a thread asking for help, read this.
Post Reply
User avatar
tentus
Inner party member
Posts: 1060
Joined: Sun Oct 31, 2010 7:56 pm
Location: Appalachia
Contact:

Math: Get Just the Sign

Post by tentus » Wed May 02, 2012 5:09 pm

You know how math.abs returns a variable, sans its sign? Does anyone there a neat trick for doing the opposite, short of using the below:

Code: Select all

function sign(x)
  if x < 0 then
    return -1
  end
  return 1
end
(And before anyone suggests it, we do not want 0.)
Kurosuke needs beta testers

User avatar
bartbes
Sex machine
Posts: 4946
Joined: Fri Aug 29, 2008 10:35 am
Location: The Netherlands
Contact:

Re: Math: Get Just the Sign

Post by bartbes » Wed May 02, 2012 5:32 pm

I only know the easy (yet probably inefficient) x/math.abs(x). (That has 0, though..)
Of course I don't know your gripe with the if, but you could shorten it to x < 0 and -1 or 1.

User avatar
molul
Party member
Posts: 264
Joined: Sun Feb 05, 2012 6:51 pm
Location: Valencia, Spain
Contact:

Re: Math: Get Just the Sign

Post by molul » Wed May 02, 2012 7:02 pm

You can define it as a math function, like this:

Code: Select all

function math.sign(x)
	return (x >= 0) and 1 or -1
end
This counts 0 as positive. If you want to identify zeros, do this:

Code: Select all

function math.sign(x)
	return (x > 0) and 1 or (x < 0) and -1 or 0
end

User avatar
Le Codex
Prole
Posts: 31
Joined: Thu Feb 09, 2017 10:56 am
Location: France
Contact:

Re: Math: Get Just the Sign

Post by Le Codex » Fri Jun 16, 2017 11:55 am

If you want to test the sign, you can just use math.abs(var) == var to test if it's positive

Example:

Code: Select all

var = 1
negvar = -1

if math.abs(var) == var then true end
if math.abs(negvar) == negvar then false end
if math.abs(negvar) == -negvar then true end

Code: Select all

if your.timeSpeed > 0 then universe:update(dt) else universe:destroy() end

Post Reply

Who is online

Users browsing this forum: Bing [Bot] and 26 guests