1

I need help on getting an interpreter to work. I have this 'bumpkin' code as a list right here.

LET A 1
GOSUB 6   <------ goes to line 6 of 'bumpkin' code (index starts at 1). 
PRINT A
PRINT B
END
LET A 2
LET B 3
RETURN   <------- returns to GOSUB 6 and continues on down list

Technically what GOSUB does is that it goes to the specified line (in this case line 6) and continues down until it hits RETURN and goes back to it again and continues on.

So technically while going in a downward fashion in the list, the GOSUB skips around the list a bit until it gets a call signal RETURN and then returns to the GOSUB line and continues downward again.

The main problem is that I don't know how to do this and append it to a new list so it becomes a new list of objects so I can execute it. The resulting new list would be:

LET A 1
LET A 2
LET B 3
PRINT A
PRINT B
END

I was curious how I would approach this. I can't use a for loop because then it'll loop through the entire 'bumpkin' code and parse them. I can't skip any lines with a loop.

Many thanks!

EDIT===========================================================EDIT

So heres my Python code so far:

oldlist = [['LET', 'A', '1'],
           ['GOSUB', '6'],
           ['PRINT', 'A'],
           ['PRINT', 'B'],
           ['END'],
           ['LET', 'A', '2'],
           ['LET', 'B', '3'],
           ['RETURN'],
           ['.']]

newlist = []

def NewLister():
    ProgramCounter = 0
    funcbool = True
    while funcbool:
        if oldlist[ProgramCounter][0] == 'LET':
            newlist.append(oldlist[ProgramCounter])
            ProgramCounter += 1
            print(newlist)
        elif oldlist[ProgramCounter][0] == 'GOSUB':
            pass # <---------------------No Idea how to get this working
        elif oldlist[ProgramCounter][0] == 'PRINT':
            pass 
        elif oldlist[ProgramCounter][0] == 'END':
            pass
4

1 回答 1

2

我认为这是一个学术练习,并且语言不相关,所以我将讨论概念而不是代码。

您需要实现一个堆栈。您将项目压入堆栈并将它们从堆栈中弹出。当您点击 GOSUB 时,将 # 行推到应该恢复执行的位置。当您按下 RETURN 时,从堆栈中弹出顶部值并在该行恢复执行。

考虑一下你的代码的这个稍微改变的版本......

LET A 1
GOSUB 6   <------ goes to line 6 of 'bumpkin' code (index starts at 1). 
PRINT A
PRINT B
END
LET A 2
LET B 3
GOSUB 10
RETURN 
DO SOMETHING 
RETURN

当您击中第一个 GOSUB 时,您将 3 压入堆栈。现在看起来像

Stack
---------
3

从第 6 行开始执行,当您点击 GOSUB 10 时,将 9 压入堆栈。现在看起来像

Stack
---------
9
3

从第 10 行开始执行。当您按下 return 时,您从堆栈中弹出顶部值,即 9。因此在第 9 行继续执行。下一个返回弹出值 3,在第 3 行继续执行。

于 2013-07-23T01:40:40.063 回答