Lua Source Code Reading (Part 1)

2017-12-16 01:00Edit this page

Lua source code series:

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:

  1. 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
  2. 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
  3. 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

Unless otherwise stated, articles on this blog are licensed under the Creative Commons Attribution 4.0 International License. Please credit the original author and source when sharing.


Tags: lua

Leave a comment

Creative Commons © 2013 — 2026 xiaocang | Theme based on fzheng.me & NexT | Hosted by Netlify