lstrlib.c 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782
  1. /*
  2. ** $Id: lstrlib.c,v 1.108 2004/11/19 16:58:43 roberto Exp roberto $
  3. ** Standard library for string operations and pattern-matching
  4. ** See Copyright Notice in lua.h
  5. */
  6. #include <ctype.h>
  7. #include <stddef.h>
  8. #include <stdio.h>
  9. #include <stdlib.h>
  10. #include <string.h>
  11. #define lstrlib_c
  12. #define LUA_LIB
  13. #include "lua.h"
  14. #include "lauxlib.h"
  15. #include "lualib.h"
  16. /* macro to `unsign' a character */
  17. #define uchar(c) ((unsigned char)(c))
  18. static int str_len (lua_State *L) {
  19. size_t l;
  20. luaL_checklstring(L, 1, &l);
  21. lua_pushinteger(L, l);
  22. return 1;
  23. }
  24. static ptrdiff_t posrelat (ptrdiff_t pos, size_t len) {
  25. /* relative string position: negative means back from end */
  26. return (pos>=0) ? pos : (ptrdiff_t)len+pos+1;
  27. }
  28. static int str_sub (lua_State *L) {
  29. size_t l;
  30. const char *s = luaL_checklstring(L, 1, &l);
  31. ptrdiff_t start = posrelat(luaL_checkinteger(L, 2), l);
  32. ptrdiff_t end = posrelat(luaL_optinteger(L, 3, -1), l);
  33. if (start < 1) start = 1;
  34. if (end > (ptrdiff_t)l) end = (ptrdiff_t)l;
  35. if (start <= end)
  36. lua_pushlstring(L, s+start-1, end-start+1);
  37. else lua_pushliteral(L, "");
  38. return 1;
  39. }
  40. static int str_reverse (lua_State *L) {
  41. size_t l;
  42. luaL_Buffer b;
  43. const char *s = luaL_checklstring(L, 1, &l);
  44. luaL_buffinit(L, &b);
  45. while (l--) luaL_putchar(&b, s[l]);
  46. luaL_pushresult(&b);
  47. return 1;
  48. }
  49. static int str_lower (lua_State *L) {
  50. size_t l;
  51. size_t i;
  52. luaL_Buffer b;
  53. const char *s = luaL_checklstring(L, 1, &l);
  54. luaL_buffinit(L, &b);
  55. for (i=0; i<l; i++)
  56. luaL_putchar(&b, tolower(uchar(s[i])));
  57. luaL_pushresult(&b);
  58. return 1;
  59. }
  60. static int str_upper (lua_State *L) {
  61. size_t l;
  62. size_t i;
  63. luaL_Buffer b;
  64. const char *s = luaL_checklstring(L, 1, &l);
  65. luaL_buffinit(L, &b);
  66. for (i=0; i<l; i++)
  67. luaL_putchar(&b, toupper(uchar(s[i])));
  68. luaL_pushresult(&b);
  69. return 1;
  70. }
  71. static int str_rep (lua_State *L) {
  72. size_t l;
  73. luaL_Buffer b;
  74. const char *s = luaL_checklstring(L, 1, &l);
  75. int n = luaL_checkint(L, 2);
  76. luaL_buffinit(L, &b);
  77. while (n-- > 0)
  78. luaL_addlstring(&b, s, l);
  79. luaL_pushresult(&b);
  80. return 1;
  81. }
  82. static int str_byte (lua_State *L) {
  83. size_t l;
  84. const char *s = luaL_checklstring(L, 1, &l);
  85. ptrdiff_t posi = posrelat(luaL_optinteger(L, 2, 1), l);
  86. ptrdiff_t pose = posrelat(luaL_optinteger(L, 3, posi), l);
  87. int n, i;
  88. if (posi <= 0) posi = 1;
  89. if ((size_t)pose > l) pose = l;
  90. if (posi > pose) return 0; /* empty interval; return no values */
  91. n = pose - posi + 1;
  92. luaL_checkstack(L, n, "string slice too long");
  93. for (i=0; i<n; i++)
  94. lua_pushinteger(L, uchar(s[posi+i-1]));
  95. return n;
  96. }
  97. static int str_char (lua_State *L) {
  98. int n = lua_gettop(L); /* number of arguments */
  99. int i;
  100. luaL_Buffer b;
  101. luaL_buffinit(L, &b);
  102. for (i=1; i<=n; i++) {
  103. int c = luaL_checkint(L, i);
  104. luaL_argcheck(L, uchar(c) == c, i, "invalid value");
  105. luaL_putchar(&b, uchar(c));
  106. }
  107. luaL_pushresult(&b);
  108. return 1;
  109. }
  110. static int writer (lua_State *L, const void* b, size_t size, void* B) {
  111. (void)L;
  112. luaL_addlstring((luaL_Buffer*) B, (const char *)b, size);
  113. return 0;
  114. }
  115. static int str_dump (lua_State *L) {
  116. luaL_Buffer b;
  117. luaL_checktype(L, 1, LUA_TFUNCTION);
  118. lua_settop(L, 1);
  119. luaL_buffinit(L,&b);
  120. if (lua_dump(L, writer, &b) != 0)
  121. luaL_error(L, "unable to dump given function");
  122. luaL_pushresult(&b);
  123. return 1;
  124. }
  125. /*
  126. ** {======================================================
  127. ** PATTERN MATCHING
  128. ** =======================================================
  129. */
  130. #define CAP_UNFINISHED (-1)
  131. #define CAP_POSITION (-2)
  132. typedef struct MatchState {
  133. const char *src_init; /* init of source string */
  134. const char *src_end; /* end (`\0') of source string */
  135. lua_State *L;
  136. int level; /* total number of captures (finished or unfinished) */
  137. struct {
  138. const char *init;
  139. ptrdiff_t len;
  140. } capture[MAX_CAPTURES];
  141. } MatchState;
  142. #define ESC '%'
  143. #define SPECIALS "^$*+?.([%-"
  144. static int check_capture (MatchState *ms, int l) {
  145. l -= '1';
  146. if (l < 0 || l >= ms->level || ms->capture[l].len == CAP_UNFINISHED)
  147. return luaL_error(ms->L, "invalid capture index");
  148. return l;
  149. }
  150. static int capture_to_close (MatchState *ms) {
  151. int level = ms->level;
  152. for (level--; level>=0; level--)
  153. if (ms->capture[level].len == CAP_UNFINISHED) return level;
  154. return luaL_error(ms->L, "invalid pattern capture");
  155. }
  156. static const char *classend (MatchState *ms, const char *p) {
  157. switch (*p++) {
  158. case ESC: {
  159. if (*p == '\0')
  160. luaL_error(ms->L, "malformed pattern (ends with `%%')");
  161. return p+1;
  162. }
  163. case '[': {
  164. if (*p == '^') p++;
  165. do { /* look for a `]' */
  166. if (*p == '\0')
  167. luaL_error(ms->L, "malformed pattern (missing `]')");
  168. if (*(p++) == ESC && *p != '\0')
  169. p++; /* skip escapes (e.g. `%]') */
  170. } while (*p != ']');
  171. return p+1;
  172. }
  173. default: {
  174. return p;
  175. }
  176. }
  177. }
  178. static int match_class (int c, int cl) {
  179. int res;
  180. switch (tolower(cl)) {
  181. case 'a' : res = isalpha(c); break;
  182. case 'c' : res = iscntrl(c); break;
  183. case 'd' : res = isdigit(c); break;
  184. case 'l' : res = islower(c); break;
  185. case 'p' : res = ispunct(c); break;
  186. case 's' : res = isspace(c); break;
  187. case 'u' : res = isupper(c); break;
  188. case 'w' : res = isalnum(c); break;
  189. case 'x' : res = isxdigit(c); break;
  190. case 'z' : res = (c == 0); break;
  191. default: return (cl == c);
  192. }
  193. return (islower(cl) ? res : !res);
  194. }
  195. static int matchbracketclass (int c, const char *p, const char *ec) {
  196. int sig = 1;
  197. if (*(p+1) == '^') {
  198. sig = 0;
  199. p++; /* skip the `^' */
  200. }
  201. while (++p < ec) {
  202. if (*p == ESC) {
  203. p++;
  204. if (match_class(c, uchar(*p)))
  205. return sig;
  206. }
  207. else if ((*(p+1) == '-') && (p+2 < ec)) {
  208. p+=2;
  209. if (uchar(*(p-2)) <= c && c <= uchar(*p))
  210. return sig;
  211. }
  212. else if (uchar(*p) == c) return sig;
  213. }
  214. return !sig;
  215. }
  216. static int singlematch (int c, const char *p, const char *ep) {
  217. switch (*p) {
  218. case '.': return 1; /* matches any char */
  219. case ESC: return match_class(c, uchar(*(p+1)));
  220. case '[': return matchbracketclass(c, p, ep-1);
  221. default: return (uchar(*p) == c);
  222. }
  223. }
  224. static const char *match (MatchState *ms, const char *s, const char *p);
  225. static const char *matchbalance (MatchState *ms, const char *s,
  226. const char *p) {
  227. if (*p == 0 || *(p+1) == 0)
  228. luaL_error(ms->L, "unbalanced pattern");
  229. if (*s != *p) return NULL;
  230. else {
  231. int b = *p;
  232. int e = *(p+1);
  233. int cont = 1;
  234. while (++s < ms->src_end) {
  235. if (*s == e) {
  236. if (--cont == 0) return s+1;
  237. }
  238. else if (*s == b) cont++;
  239. }
  240. }
  241. return NULL; /* string ends out of balance */
  242. }
  243. static const char *max_expand (MatchState *ms, const char *s,
  244. const char *p, const char *ep) {
  245. ptrdiff_t i = 0; /* counts maximum expand for item */
  246. while ((s+i)<ms->src_end && singlematch(uchar(*(s+i)), p, ep))
  247. i++;
  248. /* keeps trying to match with the maximum repetitions */
  249. while (i>=0) {
  250. const char *res = match(ms, (s+i), ep+1);
  251. if (res) return res;
  252. i--; /* else didn't match; reduce 1 repetition to try again */
  253. }
  254. return NULL;
  255. }
  256. static const char *min_expand (MatchState *ms, const char *s,
  257. const char *p, const char *ep) {
  258. for (;;) {
  259. const char *res = match(ms, s, ep+1);
  260. if (res != NULL)
  261. return res;
  262. else if (s<ms->src_end && singlematch(uchar(*s), p, ep))
  263. s++; /* try with one more repetition */
  264. else return NULL;
  265. }
  266. }
  267. static const char *start_capture (MatchState *ms, const char *s,
  268. const char *p, int what) {
  269. const char *res;
  270. int level = ms->level;
  271. if (level >= MAX_CAPTURES) luaL_error(ms->L, "too many captures");
  272. ms->capture[level].init = s;
  273. ms->capture[level].len = what;
  274. ms->level = level+1;
  275. if ((res=match(ms, s, p)) == NULL) /* match failed? */
  276. ms->level--; /* undo capture */
  277. return res;
  278. }
  279. static const char *end_capture (MatchState *ms, const char *s,
  280. const char *p) {
  281. int l = capture_to_close(ms);
  282. const char *res;
  283. ms->capture[l].len = s - ms->capture[l].init; /* close capture */
  284. if ((res = match(ms, s, p)) == NULL) /* match failed? */
  285. ms->capture[l].len = CAP_UNFINISHED; /* undo capture */
  286. return res;
  287. }
  288. static const char *match_capture (MatchState *ms, const char *s, int l) {
  289. size_t len;
  290. l = check_capture(ms, l);
  291. len = ms->capture[l].len;
  292. if ((size_t)(ms->src_end-s) >= len &&
  293. memcmp(ms->capture[l].init, s, len) == 0)
  294. return s+len;
  295. else return NULL;
  296. }
  297. static const char *match (MatchState *ms, const char *s, const char *p) {
  298. init: /* using goto's to optimize tail recursion */
  299. switch (*p) {
  300. case '(': { /* start capture */
  301. if (*(p+1) == ')') /* position capture? */
  302. return start_capture(ms, s, p+2, CAP_POSITION);
  303. else
  304. return start_capture(ms, s, p+1, CAP_UNFINISHED);
  305. }
  306. case ')': { /* end capture */
  307. return end_capture(ms, s, p+1);
  308. }
  309. case ESC: {
  310. switch (*(p+1)) {
  311. case 'b': { /* balanced string? */
  312. s = matchbalance(ms, s, p+2);
  313. if (s == NULL) return NULL;
  314. p+=4; goto init; /* else return match(ms, s, p+4); */
  315. }
  316. case 'f': { /* frontier? */
  317. const char *ep; char previous;
  318. p += 2;
  319. if (*p != '[')
  320. luaL_error(ms->L, "missing `[' after `%%f' in pattern");
  321. ep = classend(ms, p); /* points to what is next */
  322. previous = (s == ms->src_init) ? '\0' : *(s-1);
  323. if (matchbracketclass(uchar(previous), p, ep-1) ||
  324. !matchbracketclass(uchar(*s), p, ep-1)) return NULL;
  325. p=ep; goto init; /* else return match(ms, s, ep); */
  326. }
  327. default: {
  328. if (isdigit(uchar(*(p+1)))) { /* capture results (%0-%9)? */
  329. s = match_capture(ms, s, uchar(*(p+1)));
  330. if (s == NULL) return NULL;
  331. p+=2; goto init; /* else return match(ms, s, p+2) */
  332. }
  333. goto dflt; /* case default */
  334. }
  335. }
  336. }
  337. case '\0': { /* end of pattern */
  338. return s; /* match succeeded */
  339. }
  340. case '$': {
  341. if (*(p+1) == '\0') /* is the `$' the last char in pattern? */
  342. return (s == ms->src_end) ? s : NULL; /* check end of string */
  343. else goto dflt;
  344. }
  345. default: dflt: { /* it is a pattern item */
  346. const char *ep = classend(ms, p); /* points to what is next */
  347. int m = s<ms->src_end && singlematch(uchar(*s), p, ep);
  348. switch (*ep) {
  349. case '?': { /* optional */
  350. const char *res;
  351. if (m && ((res=match(ms, s+1, ep+1)) != NULL))
  352. return res;
  353. p=ep+1; goto init; /* else return match(ms, s, ep+1); */
  354. }
  355. case '*': { /* 0 or more repetitions */
  356. return max_expand(ms, s, p, ep);
  357. }
  358. case '+': { /* 1 or more repetitions */
  359. return (m ? max_expand(ms, s+1, p, ep) : NULL);
  360. }
  361. case '-': { /* 0 or more repetitions (minimum) */
  362. return min_expand(ms, s, p, ep);
  363. }
  364. default: {
  365. if (!m) return NULL;
  366. s++; p=ep; goto init; /* else return match(ms, s+1, ep); */
  367. }
  368. }
  369. }
  370. }
  371. }
  372. static const char *lmemfind (const char *s1, size_t l1,
  373. const char *s2, size_t l2) {
  374. if (l2 == 0) return s1; /* empty strings are everywhere */
  375. else if (l2 > l1) return NULL; /* avoids a negative `l1' */
  376. else {
  377. const char *init; /* to search for a `*s2' inside `s1' */
  378. l2--; /* 1st char will be checked by `memchr' */
  379. l1 = l1-l2; /* `s2' cannot be found after that */
  380. while (l1 > 0 && (init = (const char *)memchr(s1, *s2, l1)) != NULL) {
  381. init++; /* 1st char is already checked */
  382. if (memcmp(init, s2+1, l2) == 0)
  383. return init-1;
  384. else { /* correct `l1' and `s1' to try again */
  385. l1 -= init-s1;
  386. s1 = init;
  387. }
  388. }
  389. return NULL; /* not found */
  390. }
  391. }
  392. static void push_onecapture (MatchState *ms, int i) {
  393. int l = ms->capture[i].len;
  394. if (l == CAP_UNFINISHED) luaL_error(ms->L, "unfinished capture");
  395. if (l == CAP_POSITION)
  396. lua_pushinteger(ms->L, ms->capture[i].init - ms->src_init + 1);
  397. else
  398. lua_pushlstring(ms->L, ms->capture[i].init, l);
  399. }
  400. static int push_captures (MatchState *ms, const char *s, const char *e) {
  401. int i;
  402. luaL_checkstack(ms->L, ms->level, "too many captures");
  403. if (ms->level == 0 && s) { /* no explicit captures? */
  404. lua_pushlstring(ms->L, s, e-s); /* return whole match */
  405. return 1;
  406. }
  407. else { /* return all captures */
  408. for (i=0; i<ms->level; i++)
  409. push_onecapture(ms, i);
  410. return ms->level; /* number of strings pushed */
  411. }
  412. }
  413. static int str_find (lua_State *L) {
  414. size_t l1, l2;
  415. const char *s = luaL_checklstring(L, 1, &l1);
  416. const char *p = luaL_checklstring(L, 2, &l2);
  417. ptrdiff_t init = posrelat(luaL_optinteger(L, 3, 1), l1) - 1;
  418. if (init < 0) init = 0;
  419. else if ((size_t)(init) > l1) init = (ptrdiff_t)l1;
  420. if (lua_toboolean(L, 4) || /* explicit request? */
  421. strpbrk(p, SPECIALS) == NULL) { /* or no special characters? */
  422. /* do a plain search */
  423. const char *s2 = lmemfind(s+init, l1-init, p, l2);
  424. if (s2) {
  425. lua_pushinteger(L, s2-s+1);
  426. lua_pushinteger(L, s2-s+l2);
  427. return 2;
  428. }
  429. }
  430. else {
  431. MatchState ms;
  432. int anchor = (*p == '^') ? (p++, 1) : 0;
  433. const char *s1=s+init;
  434. ms.L = L;
  435. ms.src_init = s;
  436. ms.src_end = s+l1;
  437. do {
  438. const char *res;
  439. ms.level = 0;
  440. if ((res=match(&ms, s1, p)) != NULL) {
  441. lua_pushinteger(L, s1-s+1); /* start */
  442. lua_pushinteger(L, res-s); /* end */
  443. return push_captures(&ms, NULL, 0) + 2;
  444. }
  445. } while (s1++<ms.src_end && !anchor);
  446. }
  447. lua_pushnil(L); /* not found */
  448. return 1;
  449. }
  450. static int gfind_aux (lua_State *L) {
  451. MatchState ms;
  452. const char *s = lua_tostring(L, lua_upvalueindex(1));
  453. size_t ls = lua_strlen(L, lua_upvalueindex(1));
  454. const char *p = lua_tostring(L, lua_upvalueindex(2));
  455. const char *src;
  456. ms.L = L;
  457. ms.src_init = s;
  458. ms.src_end = s+ls;
  459. for (src = s + (size_t)lua_tointeger(L, lua_upvalueindex(3));
  460. src <= ms.src_end;
  461. src++) {
  462. const char *e;
  463. ms.level = 0;
  464. if ((e = match(&ms, src, p)) != NULL) {
  465. int newstart = e-s;
  466. if (e == src) newstart++; /* empty match? go at least one position */
  467. lua_pushinteger(L, newstart);
  468. lua_replace(L, lua_upvalueindex(3));
  469. return push_captures(&ms, src, e);
  470. }
  471. }
  472. return 0; /* not found */
  473. }
  474. static int gfind (lua_State *L) {
  475. luaL_checkstring(L, 1);
  476. luaL_checkstring(L, 2);
  477. lua_settop(L, 2);
  478. lua_pushinteger(L, 0);
  479. lua_pushcclosure(L, gfind_aux, 3);
  480. return 1;
  481. }
  482. static void add_s (MatchState *ms, luaL_Buffer *b,
  483. const char *s, const char *e) {
  484. lua_State *L = ms->L;
  485. if (lua_isstring(L, 3)) {
  486. const char *news = lua_tostring(L, 3);
  487. size_t l = lua_strlen(L, 3);
  488. size_t i;
  489. for (i=0; i<l; i++) {
  490. if (news[i] != ESC)
  491. luaL_putchar(b, news[i]);
  492. else {
  493. i++; /* skip ESC */
  494. if (!isdigit(uchar(news[i])))
  495. luaL_putchar(b, news[i]);
  496. else {
  497. int level = check_capture(ms, news[i]);
  498. push_onecapture(ms, level);
  499. luaL_addvalue(b); /* add capture to accumulated result */
  500. }
  501. }
  502. }
  503. }
  504. else { /* is a function */
  505. int n;
  506. lua_pushvalue(L, 3);
  507. n = push_captures(ms, s, e);
  508. lua_call(L, n, 1);
  509. if (lua_isstring(L, -1))
  510. luaL_addvalue(b); /* add return to accumulated result */
  511. else
  512. lua_pop(L, 1); /* function result is not a string: pop it */
  513. }
  514. }
  515. static int str_gsub (lua_State *L) {
  516. size_t srcl;
  517. const char *src = luaL_checklstring(L, 1, &srcl);
  518. const char *p = luaL_checkstring(L, 2);
  519. int max_s = luaL_optint(L, 4, srcl+1);
  520. int anchor = (*p == '^') ? (p++, 1) : 0;
  521. int n = 0;
  522. MatchState ms;
  523. luaL_Buffer b;
  524. luaL_argcheck(L,
  525. lua_gettop(L) >= 3 && (lua_isstring(L, 3) || lua_isfunction(L, 3)),
  526. 3, "string or function expected");
  527. luaL_buffinit(L, &b);
  528. ms.L = L;
  529. ms.src_init = src;
  530. ms.src_end = src+srcl;
  531. while (n < max_s) {
  532. const char *e;
  533. ms.level = 0;
  534. e = match(&ms, src, p);
  535. if (e) {
  536. n++;
  537. add_s(&ms, &b, src, e);
  538. }
  539. if (e && e>src) /* non empty match? */
  540. src = e; /* skip it */
  541. else if (src < ms.src_end)
  542. luaL_putchar(&b, *src++);
  543. else break;
  544. if (anchor) break;
  545. }
  546. luaL_addlstring(&b, src, ms.src_end-src);
  547. luaL_pushresult(&b);
  548. lua_pushinteger(L, n); /* number of substitutions */
  549. return 2;
  550. }
  551. /* }====================================================== */
  552. /* maximum size of each formatted item (> len(format('%99.99f', -1e308))) */
  553. #define MAX_ITEM 512
  554. /* maximum size of each format specification (such as '%-099.99d') */
  555. #define MAX_FORMAT 20
  556. static void addquoted (lua_State *L, luaL_Buffer *b, int arg) {
  557. size_t l;
  558. const char *s = luaL_checklstring(L, arg, &l);
  559. luaL_putchar(b, '"');
  560. while (l--) {
  561. switch (*s) {
  562. case '"': case '\\': case '\n': {
  563. luaL_putchar(b, '\\');
  564. luaL_putchar(b, *s);
  565. break;
  566. }
  567. case '\0': {
  568. luaL_addlstring(b, "\\000", 4);
  569. break;
  570. }
  571. default: {
  572. luaL_putchar(b, *s);
  573. break;
  574. }
  575. }
  576. s++;
  577. }
  578. luaL_putchar(b, '"');
  579. }
  580. static const char *scanformat (lua_State *L, const char *strfrmt,
  581. char *form, int *hasprecision) {
  582. const char *p = strfrmt;
  583. while (strchr("-+ #0", *p)) p++; /* skip flags */
  584. if (isdigit(uchar(*p))) p++; /* skip width */
  585. if (isdigit(uchar(*p))) p++; /* (2 digits at most) */
  586. if (*p == '.') {
  587. p++;
  588. *hasprecision = 1;
  589. if (isdigit(uchar(*p))) p++; /* skip precision */
  590. if (isdigit(uchar(*p))) p++; /* (2 digits at most) */
  591. }
  592. if (isdigit(uchar(*p)))
  593. luaL_error(L, "invalid format (width or precision too long)");
  594. if (p-strfrmt+2 > MAX_FORMAT) /* +2 to include `%' and the specifier */
  595. luaL_error(L, "invalid format (too long)");
  596. form[0] = ESC;
  597. strncpy(form+1, strfrmt, p-strfrmt+1);
  598. form[p-strfrmt+2] = 0;
  599. return p;
  600. }
  601. static int str_format (lua_State *L) {
  602. int arg = 1;
  603. size_t sfl;
  604. const char *strfrmt = luaL_checklstring(L, arg, &sfl);
  605. const char *strfrmt_end = strfrmt+sfl;
  606. luaL_Buffer b;
  607. luaL_buffinit(L, &b);
  608. while (strfrmt < strfrmt_end) {
  609. if (*strfrmt != ESC)
  610. luaL_putchar(&b, *strfrmt++);
  611. else if (*++strfrmt == ESC)
  612. luaL_putchar(&b, *strfrmt++); /* %% */
  613. else { /* format item */
  614. char form[MAX_FORMAT]; /* to store the format (`%...') */
  615. char buff[MAX_ITEM]; /* to store the formatted item */
  616. int hasprecision = 0;
  617. if (isdigit(uchar(*strfrmt)) && *(strfrmt+1) == '$')
  618. return luaL_error(L, "obsolete option (d$) to `format'");
  619. arg++;
  620. strfrmt = scanformat(L, strfrmt, form, &hasprecision);
  621. switch (*strfrmt++) {
  622. case 'c': case 'd': case 'i': {
  623. sprintf(buff, form, luaL_checkint(L, arg));
  624. break;
  625. }
  626. case 'o': case 'u': case 'x': case 'X': {
  627. sprintf(buff, form, (unsigned int)(luaL_checknumber(L, arg)));
  628. break;
  629. }
  630. case 'e': case 'E': case 'f':
  631. case 'g': case 'G': {
  632. sprintf(buff, form, luaL_checknumber(L, arg));
  633. break;
  634. }
  635. case 'q': {
  636. addquoted(L, &b, arg);
  637. continue; /* skip the `addsize' at the end */
  638. }
  639. case 's': {
  640. size_t l;
  641. const char *s = luaL_checklstring(L, arg, &l);
  642. if (!hasprecision && l >= 100) {
  643. /* no precision and string is too long to be formatted;
  644. keep original string */
  645. lua_pushvalue(L, arg);
  646. luaL_addvalue(&b);
  647. continue; /* skip the `addsize' at the end */
  648. }
  649. else {
  650. sprintf(buff, form, s);
  651. break;
  652. }
  653. }
  654. default: { /* also treat cases `pnLlh' */
  655. return luaL_error(L, "invalid option to `format'");
  656. }
  657. }
  658. luaL_addlstring(&b, buff, strlen(buff));
  659. }
  660. }
  661. luaL_pushresult(&b);
  662. return 1;
  663. }
  664. static const luaL_reg strlib[] = {
  665. {"len", str_len},
  666. {"sub", str_sub},
  667. {"reverse", str_reverse},
  668. {"lower", str_lower},
  669. {"upper", str_upper},
  670. {"char", str_char},
  671. {"rep", str_rep},
  672. {"byte", str_byte},
  673. {"format", str_format},
  674. {"dump", str_dump},
  675. {"find", str_find},
  676. {"gfind", gfind},
  677. {"gsub", str_gsub},
  678. {NULL, NULL}
  679. };
  680. /*
  681. ** Open string library
  682. */
  683. LUALIB_API int luaopen_string (lua_State *L) {
  684. luaL_openlib(L, LUA_STRLIBNAME, strlib, 0);
  685. return 1;
  686. }