Skip to content

Instantly share code, notes, and snippets.

@hanxi
Created February 16, 2023 23:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hanxi/43d2565b952acdcd2f0e53c3b4299b1b to your computer and use it in GitHub Desktop.
Save hanxi/43d2565b952acdcd2f0e53c3b4299b1b to your computer and use it in GitHub Desktop.
lua buffer test
#define LUA_LIB
#include <lua.h>
#include <lauxlib.h>
#include <string.h>
static void
dump_stack(lua_State *L, const char * name) {
int top = lua_gettop(L);
for (int i=1; i<=top; i++) {
int tp = lua_type(L, i);
fprintf(stderr, "%s i:%d tp:%s ", name, i, lua_typename(L, tp));
switch (tp) {
case LUA_TSTRING:
fprintf(stderr, "%s\n", lua_tostring(L, i));
break;
case LUA_TNIL:
fprintf(stderr, "nil\n");
break;
case LUA_TNUMBER:
{
if (lua_isinteger(L, i)) {
fprintf(stderr, "%lld\n", lua_tointeger(L, i));
} else {
fprintf(stderr, "%f\n", lua_tonumber(L, i));
}
break;
}
case LUA_TBOOLEAN:
fprintf(stderr, "%s\n", (lua_toboolean(L, i) ? "true" : "false"));
break;
default:
fprintf(stderr, "%p\n", lua_topointer(L, i));
break;
}
}
}
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);
//luaL_addvalue(&b);
dump_stack(L, "after");
}
luaL_pushresult(&b);
return 1;
}
LUAMOD_API int
luaopen_buffertest_c(lua_State * L) {
luaL_checkversion(L);
luaL_Reg l[] = {
{ "test", test },
{ NULL, NULL },
};
luaL_newlib(L, l);
return 1;
}
local buffertest = require "buffertest.c"
local a = {}
for i=1,100 do
a[i] = string.rep("x", i)
end
local ret = buffertest.test(a)
print("ok", ret)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment