diff options
| -rw-r--r-- | lstrlib.c | 32 |
1 files changed, 24 insertions, 8 deletions
| @@ -206,22 +206,38 @@ static int str_char (lua_State *L) { | |||
| 206 | } | 206 | } |
| 207 | 207 | ||
| 208 | 208 | ||
| 209 | static int writer (lua_State *L, const void *b, size_t size, void *B) { | 209 | /* |
| 210 | (void)L; | 210 | ** Buffer to store the result of 'string.dump'. It must be initialized |
| 211 | luaL_addlstring((luaL_Buffer *) B, (const char *)b, size); | 211 | ** after the call to 'lua_dump', to ensure that the function is on the |
| 212 | ** top of the stack when 'lua_dump' is called. ('luaL_buffinit' might | ||
| 213 | ** push stuff.) | ||
| 214 | */ | ||
| 215 | struct str_Writer { | ||
| 216 | int init; /* true iff buffer has been initialized */ | ||
| 217 | luaL_Buffer B; | ||
| 218 | }; | ||
| 219 | |||
| 220 | |||
| 221 | static int writer (lua_State *L, const void *b, size_t size, void *ud) { | ||
| 222 | struct str_Writer *state = (struct str_Writer *)ud; | ||
| 223 | if (!state->init) { | ||
| 224 | state->init = 1; | ||
| 225 | luaL_buffinit(L, &state->B); | ||
| 226 | } | ||
| 227 | luaL_addlstring(&state->B, (const char *)b, size); | ||
| 212 | return 0; | 228 | return 0; |
| 213 | } | 229 | } |
| 214 | 230 | ||
| 215 | 231 | ||
| 216 | static int str_dump (lua_State *L) { | 232 | static int str_dump (lua_State *L) { |
| 217 | luaL_Buffer b; | 233 | struct str_Writer state; |
| 218 | int strip = lua_toboolean(L, 2); | 234 | int strip = lua_toboolean(L, 2); |
| 219 | luaL_checktype(L, 1, LUA_TFUNCTION); | 235 | luaL_checktype(L, 1, LUA_TFUNCTION); |
| 220 | lua_settop(L, 1); | 236 | lua_settop(L, 1); /* ensure function is on the top of the stack */ |
| 221 | luaL_buffinit(L,&b); | 237 | state.init = 0; |
| 222 | if (lua_dump(L, writer, &b, strip) != 0) | 238 | if (lua_dump(L, writer, &state, strip) != 0) |
| 223 | return luaL_error(L, "unable to dump given function"); | 239 | return luaL_error(L, "unable to dump given function"); |
| 224 | luaL_pushresult(&b); | 240 | luaL_pushresult(&state.B); |
| 225 | return 1; | 241 | return 1; |
| 226 | } | 242 | } |
| 227 | 243 | ||
