本文内容基于版本:Lua 5.3.0
global_State与lua_State结构的关联
通过luaL_newstate函数创建虚拟机时,第一块申请的内存将用来存储lua_State(主线程)和global_State(全局状态机)实例。为了避免内存碎片的产生,同时减少内存分配和释放的次数,Lua采用了一个小技巧:利用一个LG结构,把分配lua_State和global_State的行为关联在一起。
// luaconf.h /* @@ LUA_EXTRASPACE defines the size of a raw memory area associated with ** a Lua state with very fast access. ** CHANGE it if you need a different size. */ #define LUA_EXTRASPACE (sizeof(void *)) // lstate.c /* ** thread state + extra space */ typedef struct LX { lu_byte extra_[LUA_EXTRASPACE]; lua_State l; } LX; /* ** Main thread combines a thread state and the global state */ typedef struct LG { LX l; global_State g; } LG;
时间: 2024-11-08 04:52:47