aboutsummaryrefslogtreecommitdiff
path: root/lstrlib.c
diff options
context:
space:
mode:
authorRoberto Ierusalimschy <roberto@inf.puc-rio.br>2019-10-23 10:31:02 -0300
committerRoberto Ierusalimschy <roberto@inf.puc-rio.br>2019-10-23 10:31:02 -0300
commit6e285e539274920830eeec5cd2dde5eeca5863e4 (patch)
tree1d2a19d8f576441f647950aa3352dd1c1c77f02a /lstrlib.c
parentb8cdea01908f8d436e9d5a73d640645ea52d5f65 (diff)
downloadlua-6e285e539274920830eeec5cd2dde5eeca5863e4.tar.gz
lua-6e285e539274920830eeec5cd2dde5eeca5863e4.tar.bz2
lua-6e285e539274920830eeec5cd2dde5eeca5863e4.zip
More pious implementation of 'string.dump'
In 'str__dump', the call to 'lua_dump' assumes the function is on the top of the stack, but the manual allows 'luaL_buffinit' to push stuff on the stack (although the current implementation does not). So, the call to 'luaL_buffinit' must come after the call to 'lua_dump'.
Diffstat (limited to 'lstrlib.c')
-rw-r--r--lstrlib.c32
1 files changed, 24 insertions, 8 deletions
diff --git a/lstrlib.c b/lstrlib.c
index a5f60b63..946461a8 100644
--- a/lstrlib.c
+++ b/lstrlib.c
@@ -206,22 +206,38 @@ static int str_char (lua_State *L) {
206} 206}
207 207
208 208
209static 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*/
215struct str_Writer {
216 int init; /* true iff buffer has been initialized */
217 luaL_Buffer B;
218};
219
220
221static 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
216static int str_dump (lua_State *L) { 232static 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