码迷,mamicode.com
首页 > 其他好文 > 详细

Lua字符串

时间:2015-06-08 19:22:44      阅读:166      评论:0      收藏:0      [点我收藏+]

标签:

       本文内容基于版本:Lua 5.3.0

TString结构


• TString结构的声明

       Lua字符串对应的C结构为TString,该类型定义在lobject.h中。

// lobject.h
/*
** Common Header for all collectable objects (in macro form, to be
** included in other objects)
*/
#define CommonHeader    GCObject *next; lu_byte tt; lu_byte marked

// lobject.h
/*
** Header for string value; string bytes follow the end of this structure
** (aligned according to ‘UTString‘; see next).
*/
typedef struct TString {
  CommonHeader;
  lu_byte extra;  /* reserved words for short strings; "has hash" for longs */
  unsigned int hash;
  size_t len;  /* number of characters in string */
  struct TString *hnext;  /* linked list for hash table */
} TString;

       CommonHeader : 用于GC的信息。

       extra : 用于记录辅助信息。对于短字符串,该字段用来标记字符串是否为保留字,用于词法分析器中对保留字的快速判断;对于长字符串,该字段将用于惰性求哈希值的策略(第一次用到才进行哈希)。

       hash : 记录字符串的hash值,可以用来加快字符串的匹配和查找。

       len : 由于Lua并不以‘\0‘字符结尾来识别字符串的长度,因此需要一个len域来记录其长度。

       hnext : hash table中相同hash值的字符串将串成一个列表,hnext域为指向下一个列表节点的指针。

TString存储结构图

       Lua字符串的数据内容部分并未分配独立的内存来存储,而是直接追加在TString结构的后面TString存储结构如下图:

       技术分享

        • Lua字符串对象 = TString结构 + 实际字符串
        • TString结构 = GCObject *指针 + 字符串信息数据

Lua字符串

标签:

原文地址:http://www.cnblogs.com/heartchord/p/4561308.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!