lua-users home
lua-l archive

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


On 22/10/2011 15:03, liam mail wrote:

I propose to rewrite the macro with something like:

#define lua_getglobal(L,s) \
        do { const char* S=s; lua_pushglobaltable(L); lua_getfield(L, -1, S);
lua_remove(L, -2); } while(0)


Yes this is correct as you are using a relative rather than absolute
address and your proposed solution looks good for relative indexes,
although I would question the do while block. The do while block scope
is recommended by numerous FAQs, books et al, yet with a high enough
compiler warning level and the wrong compiler it will generate user
warnings in code. *

The 'do {} while(0)' trick is not just about limiting scope, its primary purpose is to guarantee that you can safely use the macro like a regular function in all contexts. Without the dummy loop you'd get unexpected results e.g. when using:

if (foo)
    lua_getglobal(L, x);

I'd also expect the trick to be common enough to not generate a warning in most compilers, but that's only a guess. There is however another potential source of warnings: The variable 'S' might shadow another identifier declared outside. It should at least be changed to a less commonly used name.

I guess the only safe solution is to make lua_getglobal() a real function.

Regards,
Ingo