2
0

lstrlib.c 20 KB

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