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 2021-08-19 19:54  Ron Ngai  阅读(334)  评论(0编辑  收藏  举报

导航