2012-07-08 49 views
1

使用Lua的C-API是有连接两个LuaL_Buffer秒的有效方法?我宁愿不做任何不必要的memcopys,并想要luaL_pushresult()消耗的结果。该缓冲区包含嵌入零,所以我不能将它们转换为字符数组,并使用luaL_addstring()。修改任一缓冲区是可以接受的。如何连接两个Lua luaL_Buffer ojbects?

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

你可以推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 
2

创建在C水平整个字符串,而不是和使用luaL_addlstring,这样空字符可以安全地加入缓冲液。