RosettaCodeData/Task/Execute-Brain-/Zkl/execute-brain--1.zkl
2023-07-01 13:44:08 -04:00

29 lines
1,012 B
Text

fcn bf(pgm,input=""){ pgm=pgm.text; // handle both String and Data
const CELLS=0d30_000;
if(Void==pgm.span("[","]")){ println("Mismatched brackets"); return(); }
fcn(code,z,jmpTable){ // build jump table (for [ & ])
if(span:=code.span("[","]")){
a,b:=span; b+=a-1; jmpTable[a+z]=b+z; jmpTable[b+z]=a+z;
self.fcn(code[a+1,b-a-1],z+a+1,jmpTable);
self.fcn(code[b+1,*],z+b+1,jmpTable);
}
}(pgm,0,jmpTable:=Dictionary());
tape:=CELLS.pump(Data(CELLS,Int),0);
ip:=dp:=0; input=input.walker();
try{
while(1){
switch(pgm[ip]){
case(">"){ dp+=1 }
case("<"){ dp-=1 }
case("+"){ tape[dp]=tape[dp]+1 }
case("-"){ tape[dp]=tape[dp]-1 }
case("."){ tape[dp].toChar().print() }
case(","){ c:=input._next(); tape[dp]=(c and input.value or 0); }
case("["){ if(0==tape[dp]){ ip=jmpTable[ip] }}
case("]"){ if(tape[dp]) { ip=jmpTable[ip] }}
}
ip+=1;
} // while
}catch(IndexError){} // read past end of tape == end of program
}