Understand the difference between Stack-Based and Register-Based Bytecode
masterThe implementation in this book uses a stack-based bytecode instruction set. This is chosen for its simplicity in compiler generation and execution compared to register-based architectures.
Stack-Based Bytecode
Instructions operate by pushing and popping values from a stack. To perform an operation like c = a + b, multiple instructions are required:
load <a>: Push local variableaonto the stack.load <b>: Push local variablebonto the stack.add: Pop two values, add them, and push the result.store <c>: Pop the result and store it in local variablec.
Register-Based Bytecode
Instructions can read inputs from and store outputs directly into specific stack slots (local variables). The same operation c = a + b would be a single instruction:
add <a> <b> <c>: Read values fromaandb, add them, and store the result inc.
While register-based VMs (like Lua 5.0) can be faster due to fewer instruction dispatches, stack-based VMs are easier to implement for a first compiler.