Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoiding string copying in Lua

Tags:

performance

c

lua

Say I have a C program which wants to call a very simple Lua function with two strings (let's say two comma separated lists, returning true if the lists intersect at all, false if not).

The obvious way to do this is to push them onto the stack with lua_pushstring, which works fine, however, from the doc it looks like lua_pushstring but makes a copy of the string for Lua to work with.

That means that to cross over to the Lua function is going to require two string copies which I could avoid by rewriting the Lua function in C. Is there any way to arrange things so that the existing C strings could be reused on the Lua side for the sake of performance (or would the strcpy cost pale into insignificance anyway)?

From my investigation so far (my first couple of hours looking seriously at Lua), lite userdata seems like the sort of thing I want, but in the form of a string.

like image 848
Matt Sheppard Avatar asked Jul 14 '26 20:07

Matt Sheppard


1 Answers

No. You cannot forbid Lua making a copy of the string when you call lua_pushstring().

Reason: Unless, the internal garbage collector would not be able to free unused memory (like your 2 input strings).

Even if you use the light user data functionality (which would be an overkill in this case), you would have to use lua_pushstring() later, when the Lua program asks for the string.

like image 196
ulrichb Avatar answered Jul 16 '26 08:07

ulrichb



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!