Try my functions

Ivers, Doug E Doug_Ivers at lord.com
Thu Mar 13 09:45:01 EST 2003


You may find the following functions useful, if not in themselves, then
perhaps they will help you in terms of style.

I typically use these functions in other functions that need to check
argument types prior to usage.

Note that forceBoolean has both a function form and a command form.  Same
for forceInteger.  You may see this as overkill, but it can improve
readability and conciseness in the calling code.

In my former Java days, I learned to write tester functions.  These are not
just for debugging, but also for providing usage examples.  Type the tester
name into the messagebox to exercise the functions.

Suggestions for improvements are requested.

-- D


function forceBoolean B,defaultB
  -- if no defaultB, defaults to false
  -- alt:  (B = true) or value(B = true)  -- sometimes sufficient and more appropriate
  if (B <> true and B <> false) then return (defaultB = true)  -- don't assume defaultB is a boolean
  else return B
end forceBoolean
on forceBoolean @B,defaultB
  put forceBoolean(B,defaultB) into B
end forceBoolean
on testForceBoolean
  answer "forceBoolean(b) = "& forceBoolean(b)
  put "t" into b2
  forceBoolean b2,true
  answer "forceBoolean b2 = "& b2
end testForceBoolean

function forceInteger N lowestN highestN
  -- lowestN <= highestN is not verified herein
  -- trunc() used, round() is an alternative
  if (N is not a number) then put 0 into N
  if (lowestN is a number and N < lowestN) then return trunc(lowestN)
  if (highestN is a number and N > highestN) then return trunc(highestN)
  return trunc(N)
end forceInteger
on forceInteger @N lowestN highestN
  put forceInteger(N,lowestN,highestN) into N
end forceInteger
on testForceInteger
  answer "forceInteger(1.234) = "& forceInteger(1.234)
  answer format("forceInteger(\"int\") = ")& forceInteger("int")
  answer "forceInteger(-4.4,2,5) = "& forceInteger(-4.4,2,5)
  answer "forceInteger(4.4,-5,-1) = "& forceInteger(4.4,-5,-1)
  put 1.234 into int
  forceInteger int
  answer "forceInteger 1.234 = "& int
  put -4.4 into int
  forceInteger int,2
   answer "forceInteger -4.4,2 = "& int
end testForceInteger

function isInteger N lowestN highestN
  -- lowestN <= highestN is not verified herein
  if (N is not an integer) then return false
  if (lowestN is a number and N < lowestN) then return false
  if (highestN is a number and N > highestN) then return false
  return true
end isInteger
on testIsInteger
  answer "isInteger(5,9) = "& isInteger(5,9)
  answer "isInteger(5,,9) = "& isInteger(5,,9)
  answer "isInteger(1.23) = "& isInteger(1.23)
end testIsInteger





More information about the use-livecode mailing list