Little trick: macro "between"

Share your advanced PureBasic knowledge/code with the community.
User avatar
graves
Enthusiast
Enthusiast
Posts: 160
Joined: Wed Oct 03, 2007 2:38 pm
Location: To the deal with a pepper

Little trick: macro "between"

Post by graves »

Hi,
For long time, on PB I missed the SQL command "between", but it's very simple using a macro:

Code: Select all

macro between(btwfld, btwfrm, btwto)
   btwfld >= btwfrm AND btwfld <= btwto
endmacro

if between(fielddata, 100, 1000)
   ... code
endif
(you can use it without paying royalties)
User avatar
Guimauve
Enthusiast
Enthusiast
Posts: 742
Joined: Wed Oct 22, 2003 2:51 am
Location: Canada

Re: Little trick: macro "between"

Post by Guimauve »

Hello everyone,

A more safe approach to this is to add parentheses around each parameters (it's a workaround to solve macro bad substitution when the macro parameter look like Var + 5) :

Code: Select all

Macro IsBetween(Value, Lower, Upper)
	
	((Value) >= (Lower) And (Value) <= (Upper))
	
EndMacro

Macro IsNotBetween(Value, Lower, Upper)
	
	((Value) < (Lower) Or (Value) > (Upper))
	
EndMacro


For Index = 5 To 15
  
  If IsBetween(Index, 8, 12)
    Debug "IsBetween 8 and 12 : " + Str(Index)
  EndIf
  
Next

For Index = 5 To 15

  If IsNotBetween(Index, 8, 12)
    Debug "IsNotBetween 8 and 12 : " + Str(Index)
  EndIf
  
Next
Best regards
Guimauve
Last edited by Guimauve on Sun May 06, 2012 7:45 am, edited 1 time in total.
Little John
Addict
Addict
Posts: 4791
Joined: Thu Jun 07, 2007 3:25 pm
Location: Berlin, Germany

Re: Little trick: macro "between"

Post by Little John »

Guimauve wrote:

Code: Select all

Macro IsNotBetween(Value, Lower, Upper)
  
  ((Value) <= (Lower) And (Value) >= (Upper))
  
EndMacro
With or without parentheses ... your Macro IsNotBetween() will not work correctly. It must use Or instead of And. Additionally, when IsBetween() uses >= and <=, IsNotBetween() shouldn't use that, but > and < instead for the sake of consistent Boolean logic:

Code: Select all

Macro IsNotBetween(Value, Lower, Upper)
  ((Value) < (Lower) Or (Value) > (Upper))
EndMacro
Regards, Little John
Last edited by Little John on Sun May 06, 2012 5:55 pm, edited 1 time in total.
User avatar
Tenaja
Addict
Addict
Posts: 1959
Joined: Tue Nov 09, 2010 10:15 pm

Re: Little trick: macro "between"

Post by Tenaja »

Yes, "technically," you should call it IsFrom() if you want to include the extremes.
Post Reply