lua-users home
lua-l archive

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


> I have the following situation: a C function that is called from Lua
> to retrieve a variable-size block of data from somewhere in my
> application. In code:

<snip>
 
> I was looking at the luaL_Buffer mechanism. I know it is intended for
> collecting lots of small strings but luaL_prepbuffer() seems useful
> for my scenario. Could I use this to allocate space and pass the
> pointer to the read_data() function, then do a luaL_addsize() and
> luaL_pushresult()? Is it guaranteed that if some Lua function raises
> an error the luaL_Buffer memory is freed?

You could use a simpler approach and have read_data accept a putc-like
function that writes one char at a time,

void read_data (void (*write_char)(char c, void *v), void *data);

and leave the buffer manipulations to luaL_Buffer facilities. A quick example:

#include <lua.h>
#include <lauxlib.h>

void read_data (void (*write_char)(char c, void *v), void *data) {
  char msg[] = "Hello World!\0";
  char *c = msg;
  while (*c) write_char(*c++, data);
}

static void write_char (char c, void *v) {
  luaL_addchar((luaL_Buffer *)v, c);
}

static int get_data (lua_State *L) {
  luaL_Buffer b;
  luaL_buffinit(L, &b);
  read_data(write_char, (void *)&b);
  luaL_pushresult(&b);
  return 1;
}

int luaopen_getdata (lua_State *L) {
  lua_pushcfunction(L, get_data);
  return 1;
}

Test:

$ lua -e 'print(require"getdata"())'
Hello World!

Cheers,
Luis.

-- 
A mathematician is a device for turning coffee into theorems.
        -- P. Erdos 

-- 
Luis Carvalho
Applied Math PhD Student - Brown University
PGP Key: E820854A <carvalho@dam.brown.edu>