lstrlib.c 20 KB

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