# Brain**** interpreter # execute the Brain**** program in the code string bf := proc( code :: string ) is local address := 1; # current data address local pc := 1; # current position in code local data := []; # data - initially empty local input := ""; # user input - initially empty local bfOperations := # table of operations and their implemntations [ ">" ~ proc() is inc address, 1 end , "<" ~ proc() is dec address, 1 end , "+" ~ proc() is inc data[ address ], 1 end , "-" ~ proc() is dec data[ address ], 1 end , "." ~ proc() is io.write( char( data[ address ] ) ) end , "," ~ proc() is # get next input character, converted to an integer while input = "" do # no input left - get the next line input := io.read() od; data[ address ] := abs( input[ 1 ] ); # remove the latest character from the input if size input < 2 then input := "" else input := input[ 2 to -1 ] fi end , "[" ~ proc() is if data[ address ] = 0 then # skip to the end of the loop local depth := 0; do inc pc, 1; if code[ pc ] = "[" then inc depth, 1 elif code[ pc ] = "]" then dec depth, 1 fi until depth < 0 fi end , "]" ~ proc() is if data[ address ] <> 0 then # skip to the start of the loop local depth := 0; do dec pc, 1; if code[ pc ] = "[" then dec depth, 1 elif code[ pc ] = "]" then inc depth, 1 fi until depth < 0 fi end ]; # execute the operations - ignore anything invalid while pc <= size code do if data[ address ] = null then data[ address ] := 0 fi; if bfOperations[ code[ pc ] ] <> null then bfOperations[ code[ pc ] ]() fi; inc pc, 1 od end; # prompt for Brain**** code and execute it, repeating until an empty code string is entered scope local code; do io.write( "BF> " ); code := io.read(); bf( code ) until code = "" epocs;