diff options
| author | Roberto Ierusalimschy <roberto@inf.puc-rio.br> | 2014-12-10 09:36:03 -0200 |
|---|---|---|
| committer | Roberto Ierusalimschy <roberto@inf.puc-rio.br> | 2014-12-10 09:36:03 -0200 |
| commit | 5c519a69d3e25f5c210a858f0abf721cd7a2fdab (patch) | |
| tree | 1f46e31684fd970962aa01985666f37fd83dfe59 | |
| parent | 6f54b07663c48c6f306e93844598b509c2db444f (diff) | |
| download | lua-5c519a69d3e25f5c210a858f0abf721cd7a2fdab.tar.gz lua-5c519a69d3e25f5c210a858f0abf721cd7a2fdab.tar.bz2 lua-5c519a69d3e25f5c210a858f0abf721cd7a2fdab.zip | |
new function 'string.packsize'
| -rw-r--r-- | lstrlib.c | 25 |
1 files changed, 24 insertions, 1 deletions
| @@ -1,5 +1,5 @@ | |||
| 1 | /* | 1 | /* |
| 2 | ** $Id: lstrlib.c,v 1.217 2014/11/11 19:40:20 roberto Exp roberto $ | 2 | ** $Id: lstrlib.c,v 1.218 2014/12/04 16:25:40 roberto Exp roberto $ |
| 3 | ** Standard library for string operations and pattern-matching | 3 | ** Standard library for string operations and pattern-matching |
| 4 | ** See Copyright Notice in lua.h | 4 | ** See Copyright Notice in lua.h |
| 5 | */ | 5 | */ |
| @@ -1258,6 +1258,28 @@ static int str_pack (lua_State *L) { | |||
| 1258 | } | 1258 | } |
| 1259 | 1259 | ||
| 1260 | 1260 | ||
| 1261 | static int str_packsize (lua_State *L) { | ||
| 1262 | Header h; | ||
| 1263 | const char *fmt = luaL_checkstring(L, 1); /* format string */ | ||
| 1264 | lua_Integer totalsize = 0; /* accumulate total size of result */ | ||
| 1265 | initheader(L, &h); | ||
| 1266 | while (*fmt != '\0') { | ||
| 1267 | int size, ntoalign; | ||
| 1268 | KOption opt = getdetails(&h, totalsize, &fmt, &size, &ntoalign); | ||
| 1269 | totalsize += ntoalign + size; | ||
| 1270 | switch (opt) { | ||
| 1271 | case Kstring: /* strings with length count */ | ||
| 1272 | case Kzstr: /* zero-terminated string */ | ||
| 1273 | luaL_argerror(L, 1, "variable-length format"); | ||
| 1274 | break; | ||
| 1275 | default: break; | ||
| 1276 | } | ||
| 1277 | } | ||
| 1278 | lua_pushinteger(L, totalsize); | ||
| 1279 | return 1; | ||
| 1280 | } | ||
| 1281 | |||
| 1282 | |||
| 1261 | /* | 1283 | /* |
| 1262 | ** Unpack an integer with 'size' bytes and 'islittle' endianness. | 1284 | ** Unpack an integer with 'size' bytes and 'islittle' endianness. |
| 1263 | ** If size is smaller than the size of a Lua integer and integer | 1285 | ** If size is smaller than the size of a Lua integer and integer |
| @@ -1374,6 +1396,7 @@ static const luaL_Reg strlib[] = { | |||
| 1374 | {"sub", str_sub}, | 1396 | {"sub", str_sub}, |
| 1375 | {"upper", str_upper}, | 1397 | {"upper", str_upper}, |
| 1376 | {"pack", str_pack}, | 1398 | {"pack", str_pack}, |
| 1399 | {"packsize", str_packsize}, | ||
| 1377 | {"unpack", str_unpack}, | 1400 | {"unpack", str_unpack}, |
| 1378 | {NULL, NULL} | 1401 | {NULL, NULL} |
| 1379 | }; | 1402 | }; |
