lua_State 结构设计

lua lua_State 结构设计

数据结构

lua的内存结构最主要有三大块,lua_State、 CallInfo、 lua_TValue。

  • lua_State里面的 stack (栈)是主要的内存结构,类型是 lua_TValue;
  • lua_TValue 主要是Value,是一个 uion,存的内容根据 lua_TValue.tt_ 标记;
  • CallInfo 用于记录函数调用信息:作用的栈区间,返回数量,调用链表。

typedef union lua_Value {
    void * p;            // LUA_TLIGHTUSERDATA
    int b;               // bool
    lua_Integer i;       // integer
    lua_Number n;        // number
    lua_CFunction f;     // function
} Value;

typedef struct lua_TValue {
    Value value_;
    int tt_;
} TValue;

typedef TValue* StkId;

struct CallInfo {
    StkId func;                // 被调用函数在栈中的位置
    StkId top;                 // 被调用函数的栈顶位置
    int nresult;               // 又多少个返回值
    int callstatus;            // 调用状态
    struct CallInfo* next;     // 下一个调用
    struct CallInfo* previous; // 上一个调用
};

typedef struct lua_State {
    StkId stack;                  // 栈
    StkId stack_last;             // 从这里开始,栈不能被使用
    StkId top;                    // 栈顶
    int stack_size;               // 大小
    struct lua_longjmp * errorjmp;
    int status;                    // 状态
    struct lua_State * next;       // 下一个lua_State,通常创建协程时会产生
    struct lua_State * previous;
    struct CallInfo base_ci;       // 和lua_State生命周期一致的函数调用信息
    struct CallInfo* ci;           // 当前运作的CallInfo
    struct global_State* l_G;      // global_state指针
    ptrdiff_t errorfunc;           // 错误函数位于栈的那个位置
    int ncalls;                    // 进行了多少次函数调用
} lua_State;

主要操作

// lua_State的创建和销毁
struct lua_State* lua_newstate(lua_Alloc alloc, void* ud);
void lua_close(struct lua_State* L);
// 入栈
void increase_top(struct lua_State* L);
void lua_pushinteger(struct lua_State* L, int integer);

// 出栈
void lua_settop(struct lua_State* L, int idx);
int lua_gettop(struct lua_State* L);
void lua_pop(struct lua_State* L);

// 取栈上的值
lua_Integer lua_tointegerx(struct lua_State* L, int idx, int* isnum);

// 创建新的函数对象CallInfo
static struct CallInfo* next_ci(struct lua_State* L, StkId func, int nresult);

posted on   Ron Ngai  阅读(390)  评论(0编辑  收藏  举报

编辑推荐:
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
阅读排行:
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 周边上新:园子的第一款马克杯温暖上架

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

点击右上角即可分享
微信分享提示