lua源码阅读(6)-函数

来源:互联网 发布:淘宝网宣纸 编辑:程序博客网 时间:2024/04/29 16:09

lua中的函数可以分为lua函数好c函数。在Lobject.h中,函数类型如下:

typedef union Closure {  CClosure c;  LClosure l;} Closure;
这是一个联合体,表示函数只可能时lua函数或c函数,c函数结构如下:

typedef struct CClosure {  ClosureHeader;  lua_CFunction f; //函数指针  TValue upvalue[1];} CClosure;
c函数结构中,主要保存了类型为int lua_func(lua_State*)的函数指针,因此在编写c函数给lua调用的时候,函数的类型都必须是这样的。uovalue为闭包时需要保存的与函数有关的值。lua中的函数与普通的c函数不同,lua中是闭包,可以理解为将数据绑定到某个特定的函数,而一般的面相对象是将函数绑定的数据。lua函数结构如下:

typedef struct LClosure {  ClosureHeader;  struct Proto *p;  UpVal *upvals[1];} LClosure;
保存lua函数信息的是struct Proto,
typedef struct Proto {  CommonHeader;//常量数组  TValue *k;  /* constants used by the function */  //指令  Instruction *code;  //内部定义的函数的信息  struct Proto **p;  /* functions defined inside the function */    int *lineinfo;  /* map from opcodes to source lines */  struct LocVar *locvars;  /* information about local variables */  TString **upvalues;  /* upvalue names */  //指向这个Proto所属的文件名  TString  *source;  int sizeupvalues;    int sizek;  /* size of `k' */    int sizecode;  int sizelineinfo;  int sizep;  /* size of `p' */  int sizelocvars;  int linedefined;  int lastlinedefined;    GCObject *gclist;  lu_byte nups;  /* number of upvalues */  //固定的参数的个数  lu_byte numparams;//是否使用可变参数 ...  lu_byte is_vararg;    lu_byte maxstacksize;} Proto;
lua的编译过程是已函数为单位的,运行也是。在全局部分就相当于在main函数中。该结构体中保存了函数所使用到的常量,变量,指令,参数信息。在函数内部还可能定义函数,编译时如图



虚拟机执行的时候,只需要遍历proto,并且执行指令数组中的指令即可。

原创粉丝点击