lua-users home
lua-l archive

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



First, I won't answer any tolua(++) things.

As to "string buffers", any Lua strings are non-modifiable. Period. So what you can do is allocate your own, internal, temporary buffer. Fill it with your data. Call lua_pushlstring(lua_State *L, const char *s, size_t len) with the data, it may contain zero bytes, no problem.

The reason the data needs to be there _before_ pushing the string, is that Lua makes a hash value of the string, and any comparisons with other strings are mere pointer operations. So, you really wouldn't (couldn't) change the string contents afterwards.

If this does not suit you, the userdata alternative is there.

-ak


1.5.2005 kello 04:14, Robert Aronsson kirjoitti:

 Its almost there :)

concider this class (C++)

class TLuaSocket
{
// Function reads iDataSize bytes from a socket and place it in pData, pData
    // must be allocated by calling lua program so we get proper
garbage collection

    int Read(char *pData,int iDataSize);
}

Now, lets pretend that I complied this with tolua++, then I could
write a lua snippet like this and execute it

socket = TLuaSocket:new()
a = string.rep(" ", 1024)
socket:Read(a,1024);
print(a)

Its vey possible that I've missed some vital point here, but is this
(string:rep(x.y)) the _only_ way to allocate a char buffer in lua  ?

/RA

On 4/30/05, Asko Kauppi <asko.kauppi@sci.fi> wrote:

If you mean allocating a buffer where the data is read (by C) and using it then in Lua, why not simply give a proper userdata block length (you
can use a structure with 'data[0]' as a "growing tail" in most
compilers).  Then, you'd attack __index metamethod to the userdata so
it seems like a usual Lua (read-only) table to Lua scripts. Would this
be enough?

Other alternative (since it's char*) would be pushing a specific length
string, but this might need an interim buffer malloced/freed by you
(since Lua strings are read-only).

Did I even touch close? :)

btw, Why is the iMaxSize a reference (you're using C++ here, right?).
That is, is the 'Read' function actually setting/writing it, is it
input only, or mixed input-output.  Please specify.

-ak

30.4.2005 kello 13:26, Robert Aronsson kirjoitti:

 Hi guys,

Excuse me if this has been posted before but I cant find it in the
archives.

I need to call a c function from lua that looks like this

bool Read(char *pData,unsigned int &iMaxSize);

The Read function will read some data of max iMaxSize and place it in
the pre-allocated pData char pointer, returns true on success or false
on failure.

My question is, how do I pre-allocate an array in Lua that I can use
to send into this C function? (without doing a for loop that adds
strings to a variable for example)

Best Regards,
Robert Aronsson