When trying to dump a function’s bytecode to a buffer, I was surprised to see the Lua stack change size. Docs say that lua_dump should not push nor pop the stack. Some functions do and some do not.
This does:
function f() print "x" end
This does not:
function f() return "x" end
lua_dump in both cases returns 0 (no error).
I assume it has something to do with the use of the print function, but I can’t find any docs describing what is going on or what might be contained in the userdata. ..or whether that bytecode is going to be usable without it.
sample code:
static int base64_write(lua_State* L, unsigned char* str, size_t len,
struct luaL_Buffer *buf)
{
unsigned int idx;
char code[5];
for (idx=0; idx<len; idx++){
sprintf(code, "\\%03d", (unsigned int) str[idx]);
//printf(code);
luaL_addlstring(buf, code, 4);
}
//printf("\n");
return 0;
}
void dump_function(lua_State* L){
int stack_sz;
int res;
luaL_Buffer buf;
luaL_buffinit(L, &buf);
// ** test 1 - works as expected
lua_settop(L,0);
luaL_dostring(L, "function f() return 'x' end");
lua_getglobal(L, "f");
printf("stack sz: %i\n", lua_gettop(L));
res = lua_dump(L, (lua_Writer)base64_write, &buf);
printf("stack sz: %i\n", lua_gettop(L));
// ** test 2 - not as expected
lua_settop(L,0);
luaL_dostring(L, "function f() print 'x' end");
lua_getglobal(L, "f");
printf("stack sz: %i\n", lua_gettop(L));
res = lua_dump(L, (lua_Writer)base64_write, &buf);
printf("stack sz: %i\n", lua_gettop(L)); // why is this 2?
printf("type:%s\n", lua_typename(L, lua_type(L, -1))); // why userdata?
}
/* ----- Registration array ----- */
static const luaL_Reg R[] = {
{"test", dump_function},
{NULL, NULL} /* sentinel */
};
/* ----- Registration function ----- */
LUALIB_API int register_lua_tserialize(lua_State *L)
{
lua_newtable(L);
lua_setglobal(L, "test");
lua_getglobal(L, "test");
luaL_setfuncs(L, R, 0);
lua_settop(L, 0);
return 1;
}
It’s because of the usage of the buffer object. See the documentation at http://pgl.yoyo.org/luai/i/luaL_Buffer
You need to call luaL_pushresult to get rid of the intermediate buffer stack items.