File Line 巨集

lua-users home
wiki

以下是一個 C 令牌過濾器,實作了一個 __FILE__ 和 __LINE__ 巨集系統。請注意,檔案名稱會以 '@test.lua' 的形式出現,而字串會完整顯示。您可能想要像 luaU_undump 中做的那樣,對 __FILE__ 進行一些處理。

/*
* proxy.c
* lexer proxy for Lua parser -- implements __FILE__ and __LINE__
* Luiz Henrique de Figueiredo
* This code is hereby placed in the public domain.
* Add <<#include "proxy.c">> just before the definition of luaX_next in llex.c
*/

#include <string.h>

static int nexttoken(LexState *ls, SemInfo *seminfo)
{
  int t=llex(ls,seminfo);
  if (t==TK_NAME) {
    if (strcmp(getstr(seminfo->ts),"__FILE__")==0) {
      t=TK_STRING;
      seminfo->ts = ls->source;
    }
    else if (strcmp(getstr(seminfo->ts),"__LINE__")==0) {
      t=TK_NUMBER;
      seminfo->r = ls->linenumber;
    }
  }
  return t;
}

#define llex nexttoken

對應的純 Lua 程式碼可能是

function __FILE__() return debug.getinfo(2,'S').source end
function __LINE__() return debug.getinfo(2, 'l').currentline end

RecentChanges · preferences
edit · history
最後編輯時間為 2007 年 9 月 18 日 上午 4:11 GMT (比較)