lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


> In our game dev environment, we decide to do some kind of preprocessing
> to limit both expensive call to C and memory use of variable.
> 
> We use a custom C parser, but this can be implemented with token-filter.

Here is a token filter written in C that expands constants from a table.
For simplicity, I've used a global table named _CONSTANTS.
--lhf

/*
* proxy.c
* lexer proxy for Lua parser -- implements constant replacement
* Luiz Henrique de Figueiredo <lhf@tecgraf.puc-rio.br>
* 24 May 2007 09:44:31
* This code is hereby placed in the public domain.
* Add <<#include "proxy.c">> just before the definition of luaX_next in llex.c
*/

static int nexttoken(LexState *ls, SemInfo *seminfo)
{
 lua_State *L=ls->L;
 int n=0;
 int t=llex(ls,seminfo);
 if (t==TK_NAME)
 {
  n++;
  lua_getglobal(L,"_CONSTANTS");
  if (lua_istable(L,-1))
  {
   lua_getfield(L,-1,getstr(seminfo->ts));
   n++;
   switch (lua_type(L,-1))
   {
    case LUA_TNUMBER:
      seminfo->r=lua_tonumber(L,-1);
      t=TK_NUMBER;
      break;
    case LUA_TSTRING:
      seminfo->ts=rawtsvalue(&L->top[-1]);
      t=TK_STRING;
      break;
    case LUA_TBOOLEAN:
      t=lua_toboolean(L,-1) ? TK_TRUE : TK_FALSE;
      break;
    default:
      break;
   }
  }
 }
 lua_pop(L,n);
 return t;
}

#define llex nexttoken