lstrlib.c 20 KB

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