[M3devel] add/subtract in Quake

Jay K jay.krell at cornell.edu
Thu Jul 1 16:45:18 CEST 2010


Folks might find this amusing or useful.    I actually think I'm going to use it, just for the numbers 0-64.It implements addition and subtraction for a fixed range, here 0-9999Global variables are only used for initialization.Thereafter, just global constants (no enforcement of that, but I think it could be done by having initialization return them).
Approach is that adding 1 to a single digit can be done with a small map.Adding 1 to multiple digits can be done using multiple variables and checking for "wraparound" to 0 (the table maps 9 to 0).You count up to 9999, filling in an Add1 and Sub1 hash table as you go up.  I don't think quake has an appropriate looping mechanism, so counting up to 9999 is done recursively.Then Add and Sub are implemented recursively like Add1{Add(a, Sub1(b)}.


local Add1 = { }local Sub1 = { }

local counter0 = 0local counter1 = 0local counter2 = 0local counter3 = 0

local proc Increment() is  local inc = { 0:1,1:2,2:3,3:4,4:5,                5:6,6:7,7:8,8:9,9:0 }  counter0 = inc{counter0}  if equal(counter0, 0)    counter1 = inc{counter1}    if equal(counter1, 0)      counter2 = inc{counter2}      if equal(counter2, 0)        counter3 = inc{counter3}      end    end  end  local c = ""  foreach d in [counter3, counter2, counter1, counter0]    if not equal(d, 0) or not equal(c, "")      c = c & d    end  end  return cend

proc InitMath_F1(a, b) is  if equal(a, "9999")    return  end  Add1{a} = b  Sub1{b} = a  InitMath_F1(b, Increment())end  
proc InitMath() is  counter0 = 0  counter1 = 0  counter2 = 0  counter3 = 0  InitMath_F1(0, Increment())end

proc Add(a, b) is  if equal(a, 0) return b end  if equal(b, 0) return a end  if equal(a, 1) return Add1{b} end  if equal(b, 1) return Add1{a} end  return Add1{Add(a, Sub1{b})}end

proc Sub(a, b) is  if equal(a, 0) return b end  if equal(b, 0) return a end  if equal(a, 1) return Sub1{b} end  if equal(b, 1) return Sub1{a} end  return Sub1{Sub(a, Sub1{b})}end

InitMath()write("99 - 40 is " & Sub(99, 40), CR)write("6 - 4 is " & Sub(6, 4), CR)write("3 + 2 is " & Add(2, 3), CR)

 		 	   		  
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://m3lists.elegosoft.com/pipermail/m3devel/attachments/20100701/9377c8c2/attachment-0001.html>


More information about the M3devel mailing list