my-basic/sample/sample07.bas

85 lines
1.5 KiB
QBasic

' This script is an example of MY-BASIC
' Copyright (c) 2011 - 2016 Wang Renxin. All rights reserved.
' For more information, see https://github.com/paladin-t/my_basic/
def reserve(m, n)
for j = len(m) to n + 2
push(m, 0)
next
enddef
def forward(cmd, i)
l = len(cmd)
while i < l and mid(cmd, i, 1) <> "]"
i = i + 1
wend
if i < l then
i = i + 1
endif
return i
enddef
def backward(cmd, i)
while i > 0 and mid(cmd, i, 1) <> "["
i = i - 1
wend
if i > 0 then
i = i - 1
endif
return i
enddef
def brainfuck(cmd)
m = list()
i = 0
cursor = 0
l = len(cmd)
while i < l
c = mid(cmd, i, 1)
if c = ">" then
cursor = cursor + 1
elseif c = "<" then
cursor = cursor - 1
elseif c = "+" then
reserve(m, cursor)
b = m(cursor)
m(cursor) = b + 1
elseif c = "-" then
reserve(m, cursor)
b = m(cursor)
m(cursor) = b - 1
elseif c = "." then
reserve(m, cursor)
print chr(m(cursor))
elseif c = "," then
reserve(m, cursor)
input ch$
m(cursor) = asc(ch$)
elseif c = "[" then
reserve(m, cursor)
b = m(cursor)
if b = 0 then
i = forward(cmd, i)
endif
elseif c = "]" then
reserve(m, cursor)
b = m(cursor)
if b <> 0 then
i = backward(cmd, i)
endif
endif
i = i + 1
wend
enddef
' This is a brainfuck interpreter written with MY-BASIC
' Try this code (without brackets): "++++++++++[>+++++++>++++++++++>+++>+<<<<-]>++.>+.+++++++..+++.>++.<<+++++++++++++++.>.+++.------.--------.>+.>."
print "BF: "
input cmd$
brainfuck(cmd$)