Sunday, September 10, 2006

Lua :: Executing a file already in memory

Been messing about with embedding lua into one of my games.

The first big hurdle turned out that Lua had no functions for loading a file into its ‘state’ that was already in memory. It has functions to compile a string into memory, and one to load a file from disk but nothing that would take an existing memory chunk and put it into state…

After much faffing about, I found you need to replicate a Lua_Reader and call lua_load.

I based the code off LoadF/GetF and luaL_loadfile

typedef struct LoadM
{
    unsigned char 
*ibuff;
    
long idx;
    
long maxlen;

    
char buff[LUAL_BUFFERSIZE];
} LoadM;


static const 
char *getM (lua_State *Lvoid *udsize_t *size)
{
    size_t lsize
;
    
size_t msize;

    
LoadM *mf = (LoadM *)ud;

    if(
mf->idx >= mf->maxlen)
        return 
NULL;

    
lsize mf->maxlen mf->idx;

    if(
lsize LUAL_BUFFERSIZE)
        
lsize LUAL_BUFFERSIZE;

    
memmove(mf->buffmf->ibuff mf->idxlsize);
    
mf->idx += lsize;

    *
size lsize;

    return (*
size 0) ? mf->buff NULL;
}

LUALIB_API int luaL_loadmem
(lua_State *Lchar *filenameunsigned char *bufflong idxlong maxlen)
{
    LoadM mf
;
    
int status;
    
int fnameindex;

    
fnameindex lua_gettop(L) + 1;  /* index of filename on the stack */

    
lua_pushfstring(L"@%s"filename);

    
mf.ibuff buff;
    
mf.idx idx;
    
mf.maxlen maxlen;

    
status lua_load(LgetM, &mflua_tostring(L, -1));

    
lua_remove(Lfnameindex);

    return 
status;
Posted by Stu on 09/10/2006 at 06:08 PM Permalink to this post.
Filed Under : Development
Tags:

(0) Comments
Share/Bookmark
Page 1 of 1 pages