lua-users home
lua-l archive

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


On 11/28/2014 07:05 AM, Santosh Kadam wrote:
Hello All, 

Is there a way to get the size of the lua_state ? I am facing occasional crash in the lua module on my embedded device. I suspect that the size might be growing beyond the allocation limit of the platform. 
 
Any inputs on this regards, please do share.

Rgds
Santosh

As you are on a embedded device I assume you open the lua_state manually with lua_newstate (lua_Alloc f, void *ud). As you can see from the Lua manual:

Creates a new, independent state. Returns NULL if cannot create the state (due to lack of memory). The argument f is the allocator function; Lua does all memory allocation for this state through this function. The second argument, ud, is an opaque pointer that Lua simply passes to the allocator in every call.

Something like this (untested):
static void theLuaAllocator (void *ud, void *ptr, size_t osize,
                                                size_t nsize) {
    /* statistics */
    *((int*)ud) += (nsize - osize); 

    /* allocation */
    (void)ud;  (void)osize;  /* not used */
       if (nsize == 0) {
         free(ptr);
         return NULL;
       }
       else
         return realloc(ptr, nsize);
     }
Then:

int theMemoryCounter = 0;
lua_State *L = lua_newstate (&theLuaAllocator, &theMemoryCounter);

That means you can write an allocator function that traces or tracks all memory allocations. If you use the standard Lua interpreter, you can easily change the lua.c file and build your own version to do the same.
--
Thomas