• 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);
    

    作者:Ron Ngai
    出处:http://rondsny.github.io
    关于作者:断码码农一枚。
    欢迎转载,但未经作者同意须在文章页面明显位置给出原文连接
    如有问题,可以通过rondsny#gmail.com 联系我,非常感谢。

  • 相关阅读:
    Git-删除文件后找回-比较文件差异
    Python-异常处理-66
    Python-包-65
    Python-序列号和模块复习-64
    python入门第二十五天--反射 通过字符串的形式操作对象中的成员
    python入门第二十五天--异常处理
    python入门第二十四天----成员修饰符 类的特殊成员
    python入门第二十四天----类的成员之属性
    python入门第二十三天-----静态字段和静态方法
    pyqt5-day4
  • 原文地址:https://www.cnblogs.com/rond/p/15163615.html
Copyright © 2020-2023  润新知