lstrlib.c 20 KB

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