lua-users home
lua-l archive

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


In case any of you are curious how I solved this problem.  First off I
wanted to copy a function from on state to another.  Here is the
solution I finally came up with.

// these are functions for reading and writing into a buffer, lua needs
this 
// for lua_dump and lua_load, some of the lua functions can get pretty
big
#define LOAD_BUF_SIZE (10 * 1024)
struct load_buf
{
	unsigned char* cur;
	unsigned char* buf;
};

int writer(lua_State* /*L*/, const void* b, long size, void* B)
{
	load_buf* buf = (load_buf*)B;
	assert(LOAD_BUF_SIZE - (buf->cur - buf->buf) >= size);
	memcpy(buf->cur, b, size);
	buf->cur += size;
	return 1;
}

const char* reader(lua_State* /*L*/, void* ud, size_t* size)
{
	load_buf* buf = (load_buf*)ud;
	*size = buf->cur - buf->buf;
	return (const char*)buf->buf;
}

// this is the guts of copying a lua function from one state to another
// -1 on the src state is the function itself, this code is in a 
// lua_next loop copying over all the variables and functions
// c functions don't need any help, just copy them straight over with
// a lua_pushcfunction, but the lua functions, functions that are
declared
// and defined in lua need special attention, string is the name of the
// function we are copying
load_buf buf;
unsigned char* cBuf = new unsigned char[LOAD_BUF_SIZE];
buf.buf = buf.cur = cBuf;
lua_dump(src, (lua_Chunkwriter)writer, &buf);
lua_load(dst, (lua_Chunkreader)reader, &buf, string);
delete[] cBuf;
lua_setglobal(dst, string);

Thanks,

jake

-----Original Message-----
From: Jacob Devore 
Sent: Tuesday, January 04, 2005 6:38 PM
To: Lua list
Subject: RE: Is there any easy way to copy lua functions(not c
functions)

Okay, so I've been hacking on this for a while and can't get it to work.
Here's the code I have so far.  Do you guys see anything wrong with it?

luaL_Buffer b;
luaL_buffinit(src,&b);
lua_dump(src, (lua_Chunkwriter)writer, &b);
luaL_loadbuffer(dst, b.buffer, b.p - b.buffer, string);

src = the lua state I'm copying the function from
dst = the lua state I'm copying the function to
string = the name of the function from src

Thanks,

jake

-----Original Message-----
From: Joseph Stewart [mailto:joseph.stewart@gmail.com] 
Sent: Tuesday, January 04, 2005 3:27 PM
To: Lua list
Subject: Re: Is there any easy way to copy lua functions(not c
functions)

Look at the string.dump function in the lua docs... I think this is
what you want.

-joe


On Tue, 4 Jan 2005 13:23:53 -0800, Jacob Devore
<jacob.devore@tko-software.com> wrote:
>  
>  
> 
> from one environment to another? 
> 
>   
> 
> Thanks, 
> 
>   
> 
> jake 


-- 
Person who say it cannot be done should not interrupt person doing it.
 -- Old Scottish Proverb