lua-users home
lua-l archive

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


Hi,

I got one questions for the experts in here that know the internals of the underlying C code for Lua:

I did some experimental functions that use internals of Lua bypassing the official API. What I wanted to do was to go through the objects kept in L->l_G->allgc of a lua_State* L.
The code did not work and it took me a while to find out a very unexpected reason for this:

Lua defines a switch LUA_CORE which is placed in all C files belonging to Lua itself.
This switch beside some other stuff also enable a few so called tricks, one of it being LUA_NANTRICK controlled via luaconf.h (depending on a few other conditions, which were true in my case or better on my machine).
This define again redefines the type TValuefields inside lobject.h, which is used all over Lua.

So far, so good, but this lead to the fact that my own code compiled in the absence of the define LUA_CORE failed miserably:

The function
void EvilInsideDigging(lua_State* L)
{
    global_State* _G = L->l_G;
    GCObject* Li = _G->allgc;

    while(Li != NULL)
    {
        lu_byte T = gch(Li)->tt;
        if(T == LUA_TPROTO)
        {
            ...
        }
        Li = gch(Li)->next;

    }
    ...
failed due to the fact, that the access _G->allgc was misplaced by the compiler as my code assumed another memory layout of the struct global_State as the Lua core code does.

This leads for me to two questions:
1.) Can this switch not be also lead to problems in "normal" C code not poking around in internals of Lua?
2.) Why is this switch necessary at all? Why would I want code to "know" that it's part of the core and behave differently?

Fixing this behaviour is easy: Either compiling with LUA_CORE or disabling the LUA_NANTRICK both works.

But I have to say that a code setup which may lead to different memory layouts being seen by different translation units looks quite dangerous to me (O.K. in fact it is dangerous as I already proved yesterday wondering for an hour about my own stupidity to write simple C code and ending up digging around in assembler before I eventually found the problem).
Wouldn't it be better to avoid such constructs at all?

Greetings,
Seppl