Parsing & Compiling

To load and parse a Lua code:

  1. load the file with luaL_dofile.
  2. luaL_dofile will invoke luaL_loadfile, luaL_loadfile will parse the Lua code and return generated bytecode.

The first step of parsing is to create Proto from chunks. A chunk is a valid lua code. lua_load will create a Proto mainfunc, then create a closure from the Proto, then put the closure to the top of the stack for further execution.

Functions defined in the chunk will also be converted into a Proto, forming a tree of Proto with mainfunc as the root.

Parser

The Lua Parser is not generated with a parser generator because:

  • Lua has a high requirement for portability.
  • The Lua parser needs to parse the source code and generate bytecodes in the same iteration for performance reason.

In the process, FuncState will be used to store the temporary state of a function. Every FuncState has a prev pointer point to its parent. Then, Lua will traverse the FuncState tree with DFS.

However, the DFS might not have enough information while traversing. (e.g. jumping to a function which is not yet defined). Lua can backfill these missing information to the traversed tree later.