Lua処理系コード読み(1) lua_State

せっかくLua処理系いじったりしてるんだから適当にアウトプットしていこうかなと思った。ストーリーだてた解説ではなく、思いついたときに目についた構造体や関数、マクロの適当な解説を日記にのっける感じで。いつまで続けるか未定。



lua_Stateは「Lua処理系」というものの実体と考えても良い。(メインスレッド含む)スレッドごとに一つ持つ。全てのスレッドはメインスレッドから辿ることができる。

  • lua_State mainthread
    • lua_State thread (1)
    • lua_State thread (2)
    • ...
    • lua_State thread (n)

スレッドに限らず「Lua VMスタックの底」や「現在実行しているクロージャ情報」、「GC管理オブジェクト」などの全ての状態はここから辿ることができる。
ほとんどのLua APIはこのlua_Stateを第一引数とする。lua_Stateを引数としないAPIとしてはlua_Stateを作成するlua_State *luaL_newstate(void) (= lua_open)など。
# 最初にlua_Stateを作る関数がlua_Stateが必要だと困りますし当然ですが。

typedef struct lua_State lua_State;

/*
** `per thread' state
*/
struct lua_State {
  CommonHeader;
  lu_byte status;
  StkId top;  /* first free slot in the stack */
  StkId base;  /* base of current function */
  global_State *l_G;
  CallInfo *ci;  /* call info for current function */
  const Instruction *savedpc;  /* `savedpc' of current function */
  StkId stack_last;  /* last free slot in the stack */
  StkId stack;  /* stack base */
  CallInfo *end_ci;  /* points after end of ci array*/
  CallInfo *base_ci;  /* array of CallInfo's */
  int stacksize;
  int size_ci;  /* size of array `base_ci' */
  unsigned short nCcalls;  /* number of nested C calls */
  unsigned short baseCcalls;  /* nested C calls when resuming coroutine */
  lu_byte hookmask;
  lu_byte allowhook;
  int basehookcount;
  int hookcount;
  lua_Hook hook;
  TValue l_gt;  /* table of globals */
  TValue env;  /* temporary place for environments */
  GCObject *openupval;  /* list of open upvalues in this stack */
  GCObject *gclist;
  struct lua_longjmp *errorJmp;  /* current error recover point */
  ptrdiff_t errfunc;  /* current error handling function (stack index) */
};

test