lstrlib.c 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796
  1. /*
  2. ** $Id: lstrlib.c,v 1.115 2005/05/17 19:49:15 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[LUA_MAXCAPTURES];
  141. } MatchState;
  142. #define L_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 L_ESC: {
  159. if (*p == '\0')
  160. luaL_error(ms->L, "malformed pattern (ends with " LUA_QL("%%") ")");
  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 " LUA_QL("]") ")");
  168. if (*(p++) == L_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 == L_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 L_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 >= LUA_MAXCAPTURES) 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 L_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 " LUA_QL("[") " after "
  321. LUA_QL("%%f") " in pattern");
  322. ep = classend(ms, p); /* points to what is next */
  323. previous = (s == ms->src_init) ? '\0' : *(s-1);
  324. if (matchbracketclass(uchar(previous), p, ep-1) ||
  325. !matchbracketclass(uchar(*s), p, ep-1)) return NULL;
  326. p=ep; goto init; /* else return match(ms, s, ep); */
  327. }
  328. default: {
  329. if (isdigit(uchar(*(p+1)))) { /* capture results (%0-%9)? */
  330. s = match_capture(ms, s, uchar(*(p+1)));
  331. if (s == NULL) return NULL;
  332. p+=2; goto init; /* else return match(ms, s, p+2) */
  333. }
  334. goto dflt; /* case default */
  335. }
  336. }
  337. }
  338. case '\0': { /* end of pattern */
  339. return s; /* match succeeded */
  340. }
  341. case '$': {
  342. if (*(p+1) == '\0') /* is the `$' the last char in pattern? */
  343. return (s == ms->src_end) ? s : NULL; /* check end of string */
  344. else goto dflt;
  345. }
  346. default: dflt: { /* it is a pattern item */
  347. const char *ep = classend(ms, p); /* points to what is next */
  348. int m = s<ms->src_end && singlematch(uchar(*s), p, ep);
  349. switch (*ep) {
  350. case '?': { /* optional */
  351. const char *res;
  352. if (m && ((res=match(ms, s+1, ep+1)) != NULL))
  353. return res;
  354. p=ep+1; goto init; /* else return match(ms, s, ep+1); */
  355. }
  356. case '*': { /* 0 or more repetitions */
  357. return max_expand(ms, s, p, ep);
  358. }
  359. case '+': { /* 1 or more repetitions */
  360. return (m ? max_expand(ms, s+1, p, ep) : NULL);
  361. }
  362. case '-': { /* 0 or more repetitions (minimum) */
  363. return min_expand(ms, s, p, ep);
  364. }
  365. default: {
  366. if (!m) return NULL;
  367. s++; p=ep; goto init; /* else return match(ms, s+1, ep); */
  368. }
  369. }
  370. }
  371. }
  372. }
  373. static const char *lmemfind (const char *s1, size_t l1,
  374. const char *s2, size_t l2) {
  375. if (l2 == 0) return s1; /* empty strings are everywhere */
  376. else if (l2 > l1) return NULL; /* avoids a negative `l1' */
  377. else {
  378. const char *init; /* to search for a `*s2' inside `s1' */
  379. l2--; /* 1st char will be checked by `memchr' */
  380. l1 = l1-l2; /* `s2' cannot be found after that */
  381. while (l1 > 0 && (init = (const char *)memchr(s1, *s2, l1)) != NULL) {
  382. init++; /* 1st char is already checked */
  383. if (memcmp(init, s2+1, l2) == 0)
  384. return init-1;
  385. else { /* correct `l1' and `s1' to try again */
  386. l1 -= init-s1;
  387. s1 = init;
  388. }
  389. }
  390. return NULL; /* not found */
  391. }
  392. }
  393. static void push_onecapture (MatchState *ms, int i) {
  394. int l = ms->capture[i].len;
  395. if (l == CAP_UNFINISHED) luaL_error(ms->L, "unfinished capture");
  396. if (l == CAP_POSITION)
  397. lua_pushinteger(ms->L, ms->capture[i].init - ms->src_init + 1);
  398. else
  399. lua_pushlstring(ms->L, ms->capture[i].init, l);
  400. }
  401. static int push_captures (MatchState *ms, const char *s, const char *e) {
  402. int i;
  403. luaL_checkstack(ms->L, ms->level, "too many captures");
  404. if (ms->level == 0 && s) { /* no explicit captures? */
  405. lua_pushlstring(ms->L, s, e-s); /* return whole match */
  406. return 1;
  407. }
  408. else { /* return all captures */
  409. for (i=0; i<ms->level; i++)
  410. push_onecapture(ms, i);
  411. return ms->level; /* number of strings pushed */
  412. }
  413. }
  414. static int str_find (lua_State *L) {
  415. size_t l1, l2;
  416. const char *s = luaL_checklstring(L, 1, &l1);
  417. const char *p = luaL_checklstring(L, 2, &l2);
  418. ptrdiff_t init = posrelat(luaL_optinteger(L, 3, 1), l1) - 1;
  419. if (init < 0) init = 0;
  420. else if ((size_t)(init) > l1) init = (ptrdiff_t)l1;
  421. if (lua_toboolean(L, 4) || /* explicit request? */
  422. strpbrk(p, SPECIALS) == NULL) { /* or no special characters? */
  423. /* do a plain search */
  424. const char *s2 = lmemfind(s+init, l1-init, p, l2);
  425. if (s2) {
  426. lua_pushinteger(L, s2-s+1);
  427. lua_pushinteger(L, s2-s+l2);
  428. return 2;
  429. }
  430. }
  431. else {
  432. MatchState ms;
  433. int anchor = (*p == '^') ? (p++, 1) : 0;
  434. const char *s1=s+init;
  435. ms.L = L;
  436. ms.src_init = s;
  437. ms.src_end = s+l1;
  438. do {
  439. const char *res;
  440. ms.level = 0;
  441. if ((res=match(&ms, s1, p)) != NULL) {
  442. lua_pushinteger(L, s1-s+1); /* start */
  443. lua_pushinteger(L, res-s); /* end */
  444. return push_captures(&ms, NULL, 0) + 2;
  445. }
  446. } while (s1++<ms.src_end && !anchor);
  447. }
  448. lua_pushnil(L); /* not found */
  449. return 1;
  450. }
  451. static int gfind_aux (lua_State *L) {
  452. MatchState ms;
  453. size_t ls;
  454. const char *s = lua_tolstring(L, lua_upvalueindex(1), &ls);
  455. const char *p = lua_tostring(L, lua_upvalueindex(2));
  456. const char *src;
  457. ms.L = L;
  458. ms.src_init = s;
  459. ms.src_end = s+ls;
  460. for (src = s + (size_t)lua_tointeger(L, lua_upvalueindex(3));
  461. src <= ms.src_end;
  462. src++) {
  463. const char *e;
  464. ms.level = 0;
  465. if ((e = match(&ms, src, p)) != NULL) {
  466. int newstart = e-s;
  467. if (e == src) newstart++; /* empty match? go at least one position */
  468. lua_pushinteger(L, newstart);
  469. lua_replace(L, lua_upvalueindex(3));
  470. return push_captures(&ms, src, e);
  471. }
  472. }
  473. return 0; /* not found */
  474. }
  475. static int gfind (lua_State *L) {
  476. luaL_checkstring(L, 1);
  477. luaL_checkstring(L, 2);
  478. lua_settop(L, 2);
  479. lua_pushinteger(L, 0);
  480. lua_pushcclosure(L, gfind_aux, 3);
  481. return 1;
  482. }
  483. static void add_s (MatchState *ms, luaL_Buffer *b,
  484. const char *s, const char *e) {
  485. lua_State *L = ms->L;
  486. if (lua_isstring(L, 3)) {
  487. size_t l;
  488. const char *news = lua_tolstring(L, 3, &l);
  489. size_t i;
  490. for (i=0; i<l; i++) {
  491. if (news[i] != L_ESC)
  492. luaL_putchar(b, news[i]);
  493. else {
  494. i++; /* skip ESC */
  495. if (!isdigit(uchar(news[i])))
  496. luaL_putchar(b, news[i]);
  497. else {
  498. int level = check_capture(ms, news[i]);
  499. push_onecapture(ms, level);
  500. luaL_addvalue(b); /* add capture to accumulated result */
  501. }
  502. }
  503. }
  504. }
  505. else { /* is a function */
  506. int n;
  507. lua_pushvalue(L, 3);
  508. n = push_captures(ms, s, e);
  509. lua_call(L, n, 1);
  510. if (lua_isstring(L, -1))
  511. luaL_addvalue(b); /* add return to accumulated result */
  512. else
  513. lua_pop(L, 1); /* function result is not a string: pop it */
  514. }
  515. }
  516. static int str_gsub (lua_State *L) {
  517. size_t srcl;
  518. const char *src = luaL_checklstring(L, 1, &srcl);
  519. const char *p = luaL_checkstring(L, 2);
  520. int max_s = luaL_optint(L, 4, srcl+1);
  521. int anchor = (*p == '^') ? (p++, 1) : 0;
  522. int n = 0;
  523. MatchState ms;
  524. luaL_Buffer b;
  525. luaL_argcheck(L,
  526. lua_gettop(L) >= 3 && (lua_isstring(L, 3) || lua_isfunction(L, 3)),
  527. 3, "string or function expected");
  528. luaL_buffinit(L, &b);
  529. ms.L = L;
  530. ms.src_init = src;
  531. ms.src_end = src+srcl;
  532. while (n < max_s) {
  533. const char *e;
  534. ms.level = 0;
  535. e = match(&ms, src, p);
  536. if (e) {
  537. n++;
  538. add_s(&ms, &b, src, e);
  539. }
  540. if (e && e>src) /* non empty match? */
  541. src = e; /* skip it */
  542. else if (src < ms.src_end)
  543. luaL_putchar(&b, *src++);
  544. else break;
  545. if (anchor) break;
  546. }
  547. luaL_addlstring(&b, src, ms.src_end-src);
  548. luaL_pushresult(&b);
  549. lua_pushinteger(L, n); /* number of substitutions */
  550. return 2;
  551. }
  552. /* }====================================================== */
  553. /* maximum size of each formatted item (> len(format('%99.99f', -1e308))) */
  554. #define MAX_ITEM 512
  555. /* maximum size of each format specification (such as '%-099.99d') */
  556. #define MAX_FORMAT 20
  557. static void addquoted (lua_State *L, luaL_Buffer *b, int arg) {
  558. size_t l;
  559. const char *s = luaL_checklstring(L, arg, &l);
  560. luaL_putchar(b, '"');
  561. while (l--) {
  562. switch (*s) {
  563. case '"': case '\\': case '\n': {
  564. luaL_putchar(b, '\\');
  565. luaL_putchar(b, *s);
  566. break;
  567. }
  568. case '\0': {
  569. luaL_addlstring(b, "\\000", 4);
  570. break;
  571. }
  572. default: {
  573. luaL_putchar(b, *s);
  574. break;
  575. }
  576. }
  577. s++;
  578. }
  579. luaL_putchar(b, '"');
  580. }
  581. static const char *scanformat (lua_State *L, const char *strfrmt,
  582. char *form, int *hasprecision) {
  583. const char *p = strfrmt;
  584. while (strchr("-+ #0", *p)) p++; /* skip flags */
  585. if (isdigit(uchar(*p))) p++; /* skip width */
  586. if (isdigit(uchar(*p))) p++; /* (2 digits at most) */
  587. if (*p == '.') {
  588. p++;
  589. *hasprecision = 1;
  590. if (isdigit(uchar(*p))) p++; /* skip precision */
  591. if (isdigit(uchar(*p))) p++; /* (2 digits at most) */
  592. }
  593. if (isdigit(uchar(*p)))
  594. luaL_error(L, "invalid format (width or precision too long)");
  595. if (p-strfrmt+2 > MAX_FORMAT) /* +2 to include `%' and the specifier */
  596. luaL_error(L, "invalid format (too long)");
  597. form[0] = L_ESC;
  598. strncpy(form+1, strfrmt, p-strfrmt+1);
  599. form[p-strfrmt+2] = 0;
  600. return p;
  601. }
  602. static int str_format (lua_State *L) {
  603. int arg = 1;
  604. size_t sfl;
  605. const char *strfrmt = luaL_checklstring(L, arg, &sfl);
  606. const char *strfrmt_end = strfrmt+sfl;
  607. luaL_Buffer b;
  608. luaL_buffinit(L, &b);
  609. while (strfrmt < strfrmt_end) {
  610. if (*strfrmt != L_ESC)
  611. luaL_putchar(&b, *strfrmt++);
  612. else if (*++strfrmt == L_ESC)
  613. luaL_putchar(&b, *strfrmt++); /* %% */
  614. else { /* format item */
  615. char form[MAX_FORMAT]; /* to store the format (`%...') */
  616. char buff[MAX_ITEM]; /* to store the formatted item */
  617. int hasprecision = 0;
  618. arg++;
  619. strfrmt = scanformat(L, strfrmt, form, &hasprecision);
  620. switch (*strfrmt++) {
  621. case 'c': case 'd': case 'i': {
  622. sprintf(buff, form, luaL_checkint(L, arg));
  623. break;
  624. }
  625. case 'o': case 'u': case 'x': case 'X': {
  626. sprintf(buff, form, (unsigned int)(luaL_checknumber(L, arg)));
  627. break;
  628. }
  629. case 'e': case 'E': case 'f':
  630. case 'g': case 'G': {
  631. sprintf(buff, form, luaL_checknumber(L, arg));
  632. break;
  633. }
  634. case 'q': {
  635. addquoted(L, &b, arg);
  636. continue; /* skip the 'addsize' at the end */
  637. }
  638. case 's': {
  639. size_t l;
  640. const char *s = luaL_checklstring(L, arg, &l);
  641. if (!hasprecision && l >= 100) {
  642. /* no precision and string is too long to be formatted;
  643. keep original string */
  644. lua_pushvalue(L, arg);
  645. luaL_addvalue(&b);
  646. continue; /* skip the `addsize' at the end */
  647. }
  648. else {
  649. sprintf(buff, form, s);
  650. break;
  651. }
  652. }
  653. default: { /* also treat cases `pnLlh' */
  654. return luaL_error(L, "invalid option to " LUA_QL("format"));
  655. }
  656. }
  657. luaL_addlstring(&b, buff, strlen(buff));
  658. }
  659. }
  660. luaL_pushresult(&b);
  661. return 1;
  662. }
  663. static const luaL_reg strlib[] = {
  664. {"len", str_len},
  665. {"sub", str_sub},
  666. {"reverse", str_reverse},
  667. {"lower", str_lower},
  668. {"upper", str_upper},
  669. {"char", str_char},
  670. {"rep", str_rep},
  671. {"byte", str_byte},
  672. {"format", str_format},
  673. {"dump", str_dump},
  674. {"find", str_find},
  675. {"gfind", gfind},
  676. {"gsub", str_gsub},
  677. {NULL, NULL}
  678. };
  679. static void createmetatable (lua_State *L) {
  680. lua_newtable(L); /* create metatable for strings */
  681. lua_pushliteral(L, ""); /* dummy string */
  682. lua_pushvalue(L, -2);
  683. lua_setmetatable(L, -2); /* set string metatable */
  684. lua_pop(L, 1); /* pop dummy string */
  685. lua_pushvalue(L, -2); /* string library... */
  686. lua_setfield(L, -2, "__index"); /* ...is the __index metamethod */
  687. lua_getfield(L, -2, "len");
  688. lua_setfield(L, -2, "__len");
  689. lua_pop(L, 1); /* pop metatable */
  690. }
  691. /*
  692. ** Open string library
  693. */
  694. LUALIB_API int luaopen_string (lua_State *L) {
  695. luaL_openlib(L, LUA_STRLIBNAME, strlib, 0);
  696. createmetatable(L);
  697. return 1;
  698. }