如何连接两个Lua lua Buffer对象?

时间:2012-07-08 02:09:13

标签: c api lua buffer concatenation

使用Lua C-API是否有一种连接两个LuaL_Buffer的有效方法?我宁愿不做任何不必要的memcopys并希望luaL_pushresult()消耗的结果。缓冲区包含嵌入的零,因此我无法将它们转换为char数组并使用luaL_addstring()。修改任何一个缓冲区都是可以接受的。

luaL_Buffer buf1;
luaL_Buffer buf2;
luaL_buffinit(L, &buf1);
luaL_buffinit(L, &buf2);  
luaL_addchar(&buf1, "a");
luaL_addchar(&buf2, "b");
luaL_addchar(&buf1, "\0");
luaL_addchar(&buf2, "\0");
luaL_pushresult(L, Want_this(&buf1, &buf2) ); // "a\0b\0" is now the Lua string 
                                              //  at the top of the stack

2 个答案:

答案 0 :(得分:2)

改为在C级创建整个字符串并使用luaL_addlstring,这样就可以将空字符安全地添加到缓冲区中。

答案 1 :(得分:2)

您可以先将buf2推入堆栈,将其添加到buf1(弹出它),然后将buf1推入堆栈。

luaL_pushresult(L, &buf2); // push "b\0" onto the stack
luaL_addvalue(&buf1); // pop that string and add it to buf1
luaL_pushresult(L, &buf1); // push "a\0b\0" onto the stack