Stack Based?

Started by
1 comment, last by Zahlman 17 years, 8 months ago
Hi everyone, I am currently reading Greg Rosenblatt's excellent tutorials on creating a scripting language. During the first three sections he describes the creation of a variable based scripting language (add x 1 2 for x = 1 + 2). At section four he then changes it to stack based (push 1 ; push 2 ; add ; put x for x = 1 + 2). I understand the desire to easily change the scope of the language but I was wondering what the advantages of this stack based implimentation are? I'm a total noob when it comes to scripting languages so I wasn't really sure.
Advertisement
I guess that eventually it is easier to implement things like x = 1 + 2 + 3
since stackbased allows you to keep the number of operands down. You can make an interpreter that reads "command operand" in stead of "command [any_number_of operands]"

add x 1 2 3

or

push 1
push 2
push 3
add
put x

It is easier to write an interpreter when you know from the start that you read at most 2 strings. Also, it is easier to let a function like add work on the stack then work on a number of operands it has to store in the "body" of the function.

Edit: Also, you can now store values over time on the stack and operate on them later. So it is easier to pass the outcome of the sum to a new function.

x = (a+b)^2

push a
push b
add
put x
pop
pop
push x
push x
mult
put x


Greetings
A variable-based scripting language is generally much easier to write in.
A stack-based scripting language is generally much easier to interpret.

Therefore, "bytecode compilation" converts source a human-readable, variable-based scripting language into "opcodes" (one byte per instruction - not meaningful if you try to read it as text, but for example you might have '@' == push, 'A' == pop etc.) of a stack-based language.

This topic is closed to new replies.

Advertisement