lua-users home
lua-l archive

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


> > It would be nice, perhaps, if Lua had a way to define true, efficient
> > constants.

> Sounds like a job for the token-filter patch ...

I think I've posted this here, but anyway... Ah, it was a different version:
	http://lua-users.org/lists/lua-l/2007-05/msg00480.html

The code below works with the C token filter after it (it expands only numbers).

-- test.lua

MACROS= { age=23, year=2010 }

assert(loadstring[[
	print("My age is "..age.." and it's "..year)
]])()

/*
* proxy.c
* lexer proxy for Lua parser -- implements preprocessing of named constants
* Luiz Henrique de Figueiredo <lhf@tecgraf.puc-rio.br>
* 08 May 2010 11:05:02
* 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)
{
	int t=llex(ls,seminfo);
	if (t==TK_NAME) {
		lua_State *L=ls->L;
		lua_getglobal(L,"MACROS");
		if (lua_isnil(L,-1)) {
			lua_pop(L,1);
			return t;
		}
		lua_getfield(L,-1,getstr(seminfo->ts));
		if (lua_type(L,-1)==LUA_TNUMBER) {
			t=TK_NUMBER;
			seminfo->r = lua_tonumber(L,-1);
		}
		lua_pop(L,2);
	}
	return t;
}

#define llex nexttoken