Search code examples
luavm-implementation

Why is Lua designed to generate intermediate opcodes?


I was reading Lua's source code and surprisingly found that it was implemented to generate some odd instructions (e.g. GETUPVAL, FORLOOP, etc.) Then those opcodes are executed by a virtual machine. Is there any benefit to do this (compared with pure AST-based interpreter?)

Thanks.


Solution

  • Using virtual machines is an old implementation technique for languages, dating as far back to at least UCSD Pascal, BCPL, and Smalltalk. Most scripting languages now use a virtual machine. Some use a general-purpose virtual machine. Lua uses a special purpose virtual machine that reflects the semantics of the language. Hence the specialized opcodes. Lua did introduce novelty in this area by moving in version 5.0 to a register-based virtual machine, instead of a traditional stack-based one.