Lua source code series:
- Lua Source Code Reading Plan
- Lua Source Code Reading (Part 1)
- Lua Source Code Reading (Part 2)
- Lua Source Code Reading (Part 3)
- Lua Source Code Reading (Part 4)
- Lua Source Code Reading (Part 5)
- Lua Source Code Reading (Part 6)
Contents
Memory Management
I just finished reading Yun Feng’s understanding of Lua’s memory management section, and I’ve also read and commented on the corresponding code myself. The main characteristics of Lua’s memory management are:
- When the Lua VM initializes, it saves the main thread and global state on the first allocated memory block, which helps avoid memory fragmentation later
- Lua uses wrapped memory management functions that always have the exact original memory size when allocating, resizing, or freeing memory, thus saving memory that would otherwise be used for cookies like in the standard library
- Lua has wrapped memory management functions that can handle variable-length arrays, providing flexibility for data structures in the Lua language
https://github.com/xiaocang/lua-5.2.2_with_comments/releases/tag/lmem_01
Initialization
The global state section involves many subsequent parts like gc, string, table, etc., so I can only understand a little bit. Key points to understand:
- During Lua initialization, the main thread’s data stack is created differently from other threads’ data stacks
- The buff in the global state is used to handle string operations in Lua
- Lua implements a version check function to prevent multiple loading issues, which also shows that Lua was designed as an embedded language from the beginning
- For VM robustness, Lua needs to check whether memory allocation succeeds each time
https://github.com/xiaocang/lua-5.2.2_with_comments/releases/tag/global_state_02