lua-users home
lua-l archive

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


> I would actually like to pass a list of pre-defined globals to the
> chunk compiler and then have it complain about any others

It's actually pretty simple to add a hook in the parser for doing this and
much more.

In singlevaraux, near line 238, do

    ...
    else {  /* not found at current level; try upper one */
      if (singlevaraux(fs->prev, n, var, 0) == VGLOBAL) {
        checkglobal(fs, n);			<<< ADD THIS
        return VGLOBAL;
      }
    ...

Before singlevaraux, add something like this:

static void checkglobal (FuncState *fs, TString *n) {
  if (!mycheckglobal(fs->ls->L, getstr(n)))
    luaX_syntaxerror(fs->ls,
	luaO_pushfstring(fs->ls->L,"undeclared global " LUA_QS, getstr(n)));
}

This calls a user-defined function mycheckglobal that does the checking.
You may hard code the test in checkglobal if you don't want that generality.
In the more general scheme above, you need to add something like this
somewhere else in your app:

int mycheckglobal(lua_State *L, const char* name)
{
 lua_getglobal(L,"MYCHECKGLOBAL");
 if (lua_isnil(L,-1))
   lua_pop(L,1);
 else {
   int rc;
   lua_pushstring(L,name);
   lua_call(L,1,1);
   rc=lua_toboolean(L,-1);
   lua_pop(L,1);
   return rc;
 }
}

Finally, define a Lua function that does the checking:

function MYCHECKGLOBAL(x)
	return _G[x]~=nil or string.sub(x,1,1)=="G"
end

This one only likes global vars whose name begins with 'G', but you can
do anything you like here of course. Note that existing global variables
are accepted even if they do not conform to the naming convention.

Enjoy.
--lhf