Hi,
From manual:
During its normal operation, a string buffer uses a variable number of stack slots. So, while using a buffer, you cannot assume that you know where the top of the stack is. You can use the stack between successive calls to buffer operations as long as that use is balanced; that is, when you call a buffer operation, the stack is at the same level it was immediately after the previous buffer operation. (The only exception to this rule is luaL_addvalue.) After calling luaL_pushresult, the stack is back to its level when the buffer was initialized, plus the final string on its top.
Does the buffer operation include luaL_buffinit ?
test case 1 will core dump.
test case 1:
```c
static int
test(lua_State *L) {
luaL_Buffer b;
luaL_buffinit(L, &b);
dump_stack(L, "init");
int sz = lua_rawlen(L, 1);
for (size_t i = 1; i <= sz; i++) {
lua_rawgeti(L, 1, i);
dump_stack(L, "before");
printf("push:%s\n", lua_tostring(L, -1));
luaL_addstring(&b, lua_tostring(L, -1));
lua_pop(L, 1);
dump_stack(L, "after");
}
luaL_pushresult(&b);
return 1;
}
```
test case 2:
```c
static int
test(lua_State *L) {
luaL_Buffer b;
luaL_buffinit(L, &b);
dump_stack(L, "init");
int sz = lua_rawlen(L, 1);
for (size_t i = 1; i <= sz; i++) {
lua_rawgeti(L, 1, i);
dump_stack(L, "before");
printf("push:%s\n", lua_tostring(L, -1));
luaL_addvalue(&b);
dump_stack(L, "after");
}
luaL_pushresult(&b);
return 1;
}
```
My test code:
https://gist.github.com/hanxi/43d2565b952acdcd2f0e53c3b4299b1b