lstrlib.c 20 KB

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