2 ** $Id: lstrlib.c,v 1.178.1.1 2013/04/12 18:48:47 roberto Exp $
3 ** Standard library for string operations and pattern-matching
4 ** See Copyright Notice in lua.h
9 #include <sys/zfs_context.h>
21 ** maximum number of captures that a pattern can do during
22 ** pattern-matching. This limit is arbitrary.
24 #if !defined(LUA_MAXCAPTURES)
25 #define LUA_MAXCAPTURES 32
29 /* macro to `unsign' a character */
30 #define uchar(c) ((unsigned char)(c))
33 * PATCHED: add missing character macros.
36 #define tolower(C) (((C) >= 'A' && (C) <= 'Z') ? (C) - 'A' + 'a' : (C))
37 #define toupper(C) (((C) >= 'a' && (C) <= 'z') ? (C) - 'a' + 'A': (C))
38 #define iscntrl(C) ((((C) >= 0) && ((C) <= 0x1f)) || ((C) == 0x7f))
40 #define isalnum(C) (isalpha(C) || isdigit(C))
41 #define iscntrl(C) (uchar(C) <= 0x1f || uchar(C) == 0x7f)
43 #define isgraph(C) ((C) >= 0x21 && (C) <= 0x7E)
44 #define ispunct(C) (((C) >= 0x21 && (C) <= 0x2F) || \
45 ((C) >= 0x3A && (C) <= 0x40) || \
46 ((C) >= 0x5B && (C) <= 0x60) || \
47 ((C) >= 0x7B && (C) <= 0x7E))
50 * The provided version of sprintf returns a char *, but str_format expects
51 * it to return the number of characters printed. This version has the expected
54 static size_t str_sprintf(char *buf, const char *fmt, ...) {
59 len = vsnprintf(buf, INT_MAX, fmt, args);
66 static int str_len (lua_State *L) {
68 luaL_checklstring(L, 1, &l);
69 lua_pushinteger(L, (lua_Integer)l);
74 /* translate a relative string position: negative means back from end */
75 static size_t posrelat (ptrdiff_t pos, size_t len) {
76 if (pos >= 0) return (size_t)pos;
77 else if (0u - (size_t)pos > len) return 0;
78 else return len - ((size_t)-pos) + 1;
82 static int str_sub (lua_State *L) {
84 const char *s = luaL_checklstring(L, 1, &l);
85 size_t start = posrelat(luaL_checkinteger(L, 2), l);
86 size_t end = posrelat(luaL_optinteger(L, 3, -1), l);
87 if (start < 1) start = 1;
90 lua_pushlstring(L, s + start - 1, end - start + 1);
91 else lua_pushliteral(L, "");
96 static int str_reverse (lua_State *L) {
99 const char *s = luaL_checklstring(L, 1, &l);
100 char *p = luaL_buffinitsize(L, &b, l);
101 for (i = 0; i < l; i++)
103 luaL_pushresultsize(&b, l);
108 static int str_lower (lua_State *L) {
112 const char *s = luaL_checklstring(L, 1, &l);
113 char *p = luaL_buffinitsize(L, &b, l);
115 p[i] = tolower(uchar(s[i]));
116 luaL_pushresultsize(&b, l);
121 static int str_upper (lua_State *L) {
125 const char *s = luaL_checklstring(L, 1, &l);
126 char *p = luaL_buffinitsize(L, &b, l);
128 p[i] = toupper(uchar(s[i]));
129 luaL_pushresultsize(&b, l);
134 /* reasonable limit to avoid arithmetic overflow */
135 #define MAXSIZE ((~(size_t)0) >> 1)
137 static int str_rep (lua_State *L) {
139 const char *s = luaL_checklstring(L, 1, &l);
140 int n = luaL_checkint(L, 2);
141 const char *sep = luaL_optlstring(L, 3, "", &lsep);
142 if (n <= 0) lua_pushliteral(L, "");
143 else if (l + lsep < l || l + lsep >= MAXSIZE / n) /* may overflow? */
144 return luaL_error(L, "resulting string too large");
146 size_t totallen = n * l + (n - 1) * lsep;
148 char *p = luaL_buffinitsize(L, &b, totallen);
149 while (n-- > 1) { /* first n-1 copies (followed by separator) */
150 memcpy(p, s, l * sizeof(char)); p += l;
151 if (lsep > 0) { /* avoid empty 'memcpy' (may be expensive) */
152 memcpy(p, sep, lsep * sizeof(char)); p += lsep;
155 memcpy(p, s, l * sizeof(char)); /* last copy (not followed by separator) */
156 luaL_pushresultsize(&b, totallen);
162 static int str_byte (lua_State *L) {
164 const char *s = luaL_checklstring(L, 1, &l);
165 size_t posi = posrelat(luaL_optinteger(L, 2, 1), l);
166 size_t pose = posrelat(luaL_optinteger(L, 3, posi), l);
168 if (posi < 1) posi = 1;
169 if (pose > l) pose = l;
170 if (posi > pose) return 0; /* empty interval; return no values */
171 n = (int)(pose - posi + 1);
172 if (posi + n <= pose) /* (size_t -> int) overflow? */
173 return luaL_error(L, "string slice too long");
174 luaL_checkstack(L, n, "string slice too long");
176 lua_pushinteger(L, uchar(s[posi+i-1]));
181 static int str_char (lua_State *L) {
182 int n = lua_gettop(L); /* number of arguments */
185 char *p = luaL_buffinitsize(L, &b, n);
186 for (i=1; i<=n; i++) {
187 int c = luaL_checkint(L, i);
188 luaL_argcheck(L, uchar(c) == c, i, "value out of range");
191 luaL_pushresultsize(&b, n);
196 static int writer (lua_State *L, const void* b, size_t size, void* B) {
198 luaL_addlstring((luaL_Buffer*) B, (const char *)b, size);
203 static int str_dump (lua_State *L) {
205 luaL_checktype(L, 1, LUA_TFUNCTION);
208 if (lua_dump(L, writer, &b) != 0)
209 return luaL_error(L, "unable to dump given function");
217 ** {======================================================
219 ** =======================================================
223 #define CAP_UNFINISHED (-1)
224 #define CAP_POSITION (-2)
227 typedef struct MatchState {
228 int matchdepth; /* control for recursive depth (to avoid C stack overflow) */
229 const char *src_init; /* init of source string */
230 const char *src_end; /* end ('\0') of source string */
231 const char *p_end; /* end ('\0') of pattern */
233 int level; /* total number of captures (finished or unfinished) */
237 } capture[LUA_MAXCAPTURES];
241 /* recursive function */
242 static const char *match (MatchState *ms, const char *s, const char *p);
245 /* maximum recursion depth for 'match' */
246 #if !defined(MAXCCALLS)
247 #define MAXCCALLS 200
252 #define SPECIALS "^$*+?.([%-"
255 static int check_capture (MatchState *ms, int l) {
257 if (l < 0 || l >= ms->level || ms->capture[l].len == CAP_UNFINISHED)
258 return luaL_error(ms->L, "invalid capture index %%%d", l + 1);
263 static int capture_to_close (MatchState *ms) {
264 int level = ms->level;
265 for (level--; level>=0; level--)
266 if (ms->capture[level].len == CAP_UNFINISHED) return level;
267 return luaL_error(ms->L, "invalid pattern capture");
271 static const char *classend (MatchState *ms, const char *p) {
275 luaL_error(ms->L, "malformed pattern (ends with " LUA_QL("%%") ")");
280 do { /* look for a `]' */
282 luaL_error(ms->L, "malformed pattern (missing " LUA_QL("]") ")");
283 if (*(p++) == L_ESC && p < ms->p_end)
284 p++; /* skip escapes (e.g. `%]') */
295 static int match_class (int c, int cl) {
297 switch (tolower(cl)) {
298 case 'a' : res = isalpha(c); break;
299 case 'c' : res = iscntrl(c); break;
300 case 'd' : res = isdigit(c); break;
301 case 'g' : res = isgraph(c); break;
302 case 'l' : res = islower(c); break;
303 case 'p' : res = ispunct(c); break;
304 case 's' : res = isspace(c); break;
305 case 'u' : res = isupper(c); break;
306 case 'w' : res = isalnum(c); break;
307 case 'x' : res = isxdigit(c); break;
308 case 'z' : res = (c == 0); break; /* deprecated option */
309 default: return (cl == c);
311 return (islower(cl) ? res : !res);
315 static int matchbracketclass (int c, const char *p, const char *ec) {
319 p++; /* skip the `^' */
324 if (match_class(c, uchar(*p)))
327 else if ((*(p+1) == '-') && (p+2 < ec)) {
329 if (uchar(*(p-2)) <= c && c <= uchar(*p))
332 else if (uchar(*p) == c) return sig;
338 static int singlematch (MatchState *ms, const char *s, const char *p,
340 if (s >= ms->src_end)
345 case '.': return 1; /* matches any char */
346 case L_ESC: return match_class(c, uchar(*(p+1)));
347 case '[': return matchbracketclass(c, p, ep-1);
348 default: return (uchar(*p) == c);
354 static const char *matchbalance (MatchState *ms, const char *s,
356 if (p >= ms->p_end - 1)
357 luaL_error(ms->L, "malformed pattern "
358 "(missing arguments to " LUA_QL("%%b") ")");
359 if (*s != *p) return NULL;
364 while (++s < ms->src_end) {
366 if (--cont == 0) return s+1;
368 else if (*s == b) cont++;
371 return NULL; /* string ends out of balance */
375 static const char *max_expand (MatchState *ms, const char *s,
376 const char *p, const char *ep) {
377 ptrdiff_t i = 0; /* counts maximum expand for item */
378 while (singlematch(ms, s + i, p, ep))
380 /* keeps trying to match with the maximum repetitions */
382 const char *res = match(ms, (s+i), ep+1);
384 i--; /* else didn't match; reduce 1 repetition to try again */
390 static const char *min_expand (MatchState *ms, const char *s,
391 const char *p, const char *ep) {
393 const char *res = match(ms, s, ep+1);
396 else if (singlematch(ms, s, p, ep))
397 s++; /* try with one more repetition */
403 static const char *start_capture (MatchState *ms, const char *s,
404 const char *p, int what) {
406 int level = ms->level;
407 if (level >= LUA_MAXCAPTURES) luaL_error(ms->L, "too many captures");
408 ms->capture[level].init = s;
409 ms->capture[level].len = what;
411 if ((res=match(ms, s, p)) == NULL) /* match failed? */
412 ms->level--; /* undo capture */
417 static const char *end_capture (MatchState *ms, const char *s,
419 int l = capture_to_close(ms);
421 ms->capture[l].len = s - ms->capture[l].init; /* close capture */
422 if ((res = match(ms, s, p)) == NULL) /* match failed? */
423 ms->capture[l].len = CAP_UNFINISHED; /* undo capture */
428 static const char *match_capture (MatchState *ms, const char *s, int l) {
430 l = check_capture(ms, l);
431 len = ms->capture[l].len;
432 if ((size_t)(ms->src_end-s) >= len &&
433 memcmp(ms->capture[l].init, s, len) == 0)
439 static const char *match (MatchState *ms, const char *s, const char *p) {
440 if (ms->matchdepth-- == 0)
441 luaL_error(ms->L, "pattern too complex");
442 init: /* using goto's to optimize tail recursion */
443 if (p != ms->p_end) { /* end of pattern? */
445 case '(': { /* start capture */
446 if (*(p + 1) == ')') /* position capture? */
447 s = start_capture(ms, s, p + 2, CAP_POSITION);
449 s = start_capture(ms, s, p + 1, CAP_UNFINISHED);
452 case ')': { /* end capture */
453 s = end_capture(ms, s, p + 1);
457 if ((p + 1) != ms->p_end) /* is the `$' the last char in pattern? */
458 goto dflt; /* no; go to default */
459 s = (s == ms->src_end) ? s : NULL; /* check end of string */
462 case L_ESC: { /* escaped sequences not in the format class[*+?-]? */
464 case 'b': { /* balanced string? */
465 s = matchbalance(ms, s, p + 2);
467 p += 4; goto init; /* return match(ms, s, p + 4); */
468 } /* else fail (s == NULL) */
471 case 'f': { /* frontier? */
472 const char *ep; char previous;
475 luaL_error(ms->L, "missing " LUA_QL("[") " after "
476 LUA_QL("%%f") " in pattern");
477 ep = classend(ms, p); /* points to what is next */
478 previous = (s == ms->src_init) ? '\0' : *(s - 1);
479 if (!matchbracketclass(uchar(previous), p, ep - 1) &&
480 matchbracketclass(uchar(*s), p, ep - 1)) {
481 p = ep; goto init; /* return match(ms, s, ep); */
483 s = NULL; /* match failed */
486 case '0': case '1': case '2': case '3':
487 case '4': case '5': case '6': case '7':
488 case '8': case '9': { /* capture results (%0-%9)? */
489 s = match_capture(ms, s, uchar(*(p + 1)));
491 p += 2; goto init; /* return match(ms, s, p + 2) */
499 default: dflt: { /* pattern class plus optional suffix */
500 const char *ep = classend(ms, p); /* points to optional suffix */
501 /* does not match at least once? */
502 if (!singlematch(ms, s, p, ep)) {
503 if (*ep == '*' || *ep == '?' || *ep == '-') { /* accept empty? */
504 p = ep + 1; goto init; /* return match(ms, s, ep + 1); */
506 else /* '+' or no suffix */
509 else { /* matched once */
510 switch (*ep) { /* handle optional suffix */
511 case '?': { /* optional */
513 if ((res = match(ms, s + 1, ep + 1)) != NULL)
516 p = ep + 1; goto init; /* else return match(ms, s, ep + 1); */
520 case '+': /* 1 or more repetitions */
521 s++; /* 1 match already done */
523 case '*': /* 0 or more repetitions */
524 s = max_expand(ms, s, p, ep);
526 case '-': /* 0 or more repetitions (minimum) */
527 s = min_expand(ms, s, p, ep);
529 default: /* no suffix */
530 s++; p = ep; goto init; /* return match(ms, s + 1, ep); */
543 static const char *lmemfind (const char *s1, size_t l1,
544 const char *s2, size_t l2) {
545 if (l2 == 0) return s1; /* empty strings are everywhere */
546 else if (l2 > l1) return NULL; /* avoids a negative `l1' */
548 const char *init; /* to search for a `*s2' inside `s1' */
549 l2--; /* 1st char will be checked by `memchr' */
550 l1 = l1-l2; /* `s2' cannot be found after that */
551 while (l1 > 0 && (init = (const char *)memchr(s1, *s2, l1)) != NULL) {
552 init++; /* 1st char is already checked */
553 if (memcmp(init, s2+1, l2) == 0)
555 else { /* correct `l1' and `s1' to try again */
560 return NULL; /* not found */
565 static void push_onecapture (MatchState *ms, int i, const char *s,
567 if (i >= ms->level) {
568 if (i == 0) /* ms->level == 0, too */
569 lua_pushlstring(ms->L, s, e - s); /* add whole match */
571 luaL_error(ms->L, "invalid capture index");
574 ptrdiff_t l = ms->capture[i].len;
575 if (l == CAP_UNFINISHED) luaL_error(ms->L, "unfinished capture");
576 if (l == CAP_POSITION)
577 lua_pushinteger(ms->L, ms->capture[i].init - ms->src_init + 1);
579 lua_pushlstring(ms->L, ms->capture[i].init, l);
584 static int push_captures (MatchState *ms, const char *s, const char *e) {
586 int nlevels = (ms->level == 0 && s) ? 1 : ms->level;
587 luaL_checkstack(ms->L, nlevels, "too many captures");
588 for (i = 0; i < nlevels; i++)
589 push_onecapture(ms, i, s, e);
590 return nlevels; /* number of strings pushed */
594 /* check whether pattern has no special characters */
595 static int nospecials (const char *p, size_t l) {
598 if (strpbrk(p + upto, SPECIALS))
599 return 0; /* pattern has a special character */
600 upto += strlen(p + upto) + 1; /* may have more after \0 */
602 return 1; /* no special chars found */
606 static int str_find_aux (lua_State *L, int find) {
608 const char *s = luaL_checklstring(L, 1, &ls);
609 const char *p = luaL_checklstring(L, 2, &lp);
610 size_t init = posrelat(luaL_optinteger(L, 3, 1), ls);
611 if (init < 1) init = 1;
612 else if (init > ls + 1) { /* start after string's end? */
613 lua_pushnil(L); /* cannot find anything */
616 /* explicit request or no special characters? */
617 if (find && (lua_toboolean(L, 4) || nospecials(p, lp))) {
618 /* do a plain search */
619 const char *s2 = lmemfind(s + init - 1, ls - init + 1, p, lp);
621 lua_pushinteger(L, s2 - s + 1);
622 lua_pushinteger(L, s2 - s + lp);
628 const char *s1 = s + init - 1;
629 int anchor = (*p == '^');
631 p++; lp--; /* skip anchor character */
634 ms.matchdepth = MAXCCALLS;
641 lua_assert(ms.matchdepth == MAXCCALLS);
642 if ((res=match(&ms, s1, p)) != NULL) {
644 lua_pushinteger(L, s1 - s + 1); /* start */
645 lua_pushinteger(L, res - s); /* end */
646 return push_captures(&ms, NULL, 0) + 2;
649 return push_captures(&ms, s1, res);
651 } while (s1++ < ms.src_end && !anchor);
653 lua_pushnil(L); /* not found */
658 static int str_find (lua_State *L) {
659 return str_find_aux(L, 1);
663 static int str_match (lua_State *L) {
664 return str_find_aux(L, 0);
668 static int gmatch_aux (lua_State *L) {
671 const char *s = lua_tolstring(L, lua_upvalueindex(1), &ls);
672 const char *p = lua_tolstring(L, lua_upvalueindex(2), &lp);
675 ms.matchdepth = MAXCCALLS;
679 for (src = s + (size_t)lua_tointeger(L, lua_upvalueindex(3));
684 lua_assert(ms.matchdepth == MAXCCALLS);
685 if ((e = match(&ms, src, p)) != NULL) {
686 lua_Integer newstart = e-s;
687 if (e == src) newstart++; /* empty match? go at least one position */
688 lua_pushinteger(L, newstart);
689 lua_replace(L, lua_upvalueindex(3));
690 return push_captures(&ms, src, e);
693 return 0; /* not found */
697 static int str_gmatch (lua_State *L) {
698 luaL_checkstring(L, 1);
699 luaL_checkstring(L, 2);
701 lua_pushinteger(L, 0);
702 lua_pushcclosure(L, gmatch_aux, 3);
707 static void add_s (MatchState *ms, luaL_Buffer *b, const char *s,
710 const char *news = lua_tolstring(ms->L, 3, &l);
711 for (i = 0; i < l; i++) {
712 if (news[i] != L_ESC)
713 luaL_addchar(b, news[i]);
716 if (!isdigit(uchar(news[i]))) {
717 if (news[i] != L_ESC)
718 luaL_error(ms->L, "invalid use of " LUA_QL("%c")
719 " in replacement string", L_ESC);
720 luaL_addchar(b, news[i]);
722 else if (news[i] == '0')
723 luaL_addlstring(b, s, e - s);
725 push_onecapture(ms, news[i] - '1', s, e);
726 luaL_addvalue(b); /* add capture to accumulated result */
733 static void add_value (MatchState *ms, luaL_Buffer *b, const char *s,
734 const char *e, int tr) {
735 lua_State *L = ms->L;
737 case LUA_TFUNCTION: {
740 n = push_captures(ms, s, e);
745 push_onecapture(ms, 0, s, e);
749 default: { /* LUA_TNUMBER or LUA_TSTRING */
754 if (!lua_toboolean(L, -1)) { /* nil or false? */
756 lua_pushlstring(L, s, e - s); /* keep original text */
758 else if (!lua_isstring(L, -1))
759 luaL_error(L, "invalid replacement value (a %s)", luaL_typename(L, -1));
760 luaL_addvalue(b); /* add result to accumulator */
764 static int str_gsub (lua_State *L) {
766 const char *src = luaL_checklstring(L, 1, &srcl);
767 const char *p = luaL_checklstring(L, 2, &lp);
768 int tr = lua_type(L, 3);
769 size_t max_s = luaL_optinteger(L, 4, srcl+1);
770 int anchor = (*p == '^');
774 luaL_argcheck(L, tr == LUA_TNUMBER || tr == LUA_TSTRING ||
775 tr == LUA_TFUNCTION || tr == LUA_TTABLE, 3,
776 "string/function/table expected");
777 luaL_buffinit(L, &b);
779 p++; lp--; /* skip anchor character */
782 ms.matchdepth = MAXCCALLS;
784 ms.src_end = src+srcl;
789 lua_assert(ms.matchdepth == MAXCCALLS);
790 e = match(&ms, src, p);
793 add_value(&ms, &b, src, e, tr);
795 if (e && e>src) /* non empty match? */
796 src = e; /* skip it */
797 else if (src < ms.src_end)
798 luaL_addchar(&b, *src++);
802 luaL_addlstring(&b, src, ms.src_end-src);
804 lua_pushinteger(L, n); /* number of substitutions */
808 /* }====================================================== */
813 ** {======================================================
815 ** =======================================================
819 ** LUA_INTFRMLEN is the length modifier for integer conversions in
820 ** 'string.format'; LUA_INTFRM_T is the integer type corresponding to
821 ** the previous length
823 #if !defined(LUA_INTFRMLEN) /* { */
824 #if defined(LUA_USE_LONGLONG)
826 #define LUA_INTFRMLEN "ll"
827 #define LUA_INTFRM_T long long
831 #define LUA_INTFRMLEN "l"
832 #define LUA_INTFRM_T long
839 ** LUA_FLTFRMLEN is the length modifier for float conversions in
840 ** 'string.format'; LUA_FLTFRM_T is the float type corresponding to
841 ** the previous length
843 #if !defined(LUA_FLTFRMLEN)
845 #define LUA_FLTFRMLEN ""
846 #define LUA_FLTFRM_T double
851 /* maximum size of each formatted item (> len(format('%99.99f', -1e308))) */
853 /* valid flags in a format specification */
854 #define FLAGS "-+ #0"
856 ** maximum size of each format specification (such as '%-099.99d')
857 ** (+10 accounts for %99.99x plus margin of error)
859 #define MAX_FORMAT (sizeof(FLAGS) + sizeof(LUA_INTFRMLEN) + 10)
862 static void addquoted (lua_State *L, luaL_Buffer *b, int arg) {
864 const char *s = luaL_checklstring(L, arg, &l);
865 luaL_addchar(b, '"');
867 if (*s == '"' || *s == '\\' || *s == '\n') {
868 luaL_addchar(b, '\\');
871 else if (*s == '\0' || iscntrl(uchar(*s))) {
873 if (!isdigit(uchar(*(s+1))))
874 sprintf(buff, "\\%d", (int)uchar(*s));
876 sprintf(buff, "\\%03d", (int)uchar(*s));
877 luaL_addstring(b, buff);
883 luaL_addchar(b, '"');
886 static const char *scanformat (lua_State *L, const char *strfrmt, char *form) {
887 const char *p = strfrmt;
888 while (*p != '\0' && strchr(FLAGS, *p) != NULL) p++; /* skip flags */
889 if ((size_t)(p - strfrmt) >= sizeof(FLAGS)/sizeof(char))
890 luaL_error(L, "invalid format (repeated flags)");
891 if (isdigit(uchar(*p))) p++; /* skip width */
892 if (isdigit(uchar(*p))) p++; /* (2 digits at most) */
895 if (isdigit(uchar(*p))) p++; /* skip precision */
896 if (isdigit(uchar(*p))) p++; /* (2 digits at most) */
898 if (isdigit(uchar(*p)))
899 luaL_error(L, "invalid format (width or precision too long)");
901 memcpy(form, strfrmt, (p - strfrmt + 1) * sizeof(char));
902 form += p - strfrmt + 1;
909 ** add length modifier into formats
911 static void addlenmod (char *form, const char *lenmod) {
912 size_t l = strlen(form);
913 size_t lm = strlen(lenmod);
914 char spec = form[l - 1];
915 strcpy(form + l - 1, lenmod);
916 form[l + lm - 1] = spec;
921 static int str_format (lua_State *L) {
922 int top = lua_gettop(L);
925 const char *strfrmt = luaL_checklstring(L, arg, &sfl);
926 const char *strfrmt_end = strfrmt+sfl;
928 luaL_buffinit(L, &b);
929 while (strfrmt < strfrmt_end) {
930 if (*strfrmt != L_ESC)
931 luaL_addchar(&b, *strfrmt++);
932 else if (*++strfrmt == L_ESC)
933 luaL_addchar(&b, *strfrmt++); /* %% */
934 else { /* format item */
935 char form[MAX_FORMAT]; /* to store the format (`%...') */
936 char *buff = luaL_prepbuffsize(&b, MAX_ITEM); /* to put formatted item */
937 int nb = 0; /* number of bytes in added item */
939 luaL_argerror(L, arg, "no value");
940 strfrmt = scanformat(L, strfrmt, form);
941 switch (*strfrmt++) {
943 nb = str_sprintf(buff, form, luaL_checkint(L, arg));
946 case 'd': case 'i': {
947 lua_Number n = luaL_checknumber(L, arg);
948 LUA_INTFRM_T ni = (LUA_INTFRM_T)n;
949 lua_Number diff = n - (lua_Number)ni;
950 luaL_argcheck(L, -1 < diff && diff < 1, arg,
951 "not a number in proper range");
952 addlenmod(form, LUA_INTFRMLEN);
953 nb = str_sprintf(buff, form, ni);
956 case 'o': case 'u': case 'x': case 'X': {
957 lua_Number n = luaL_checknumber(L, arg);
958 unsigned LUA_INTFRM_T ni = (unsigned LUA_INTFRM_T)n;
959 lua_Number diff = n - (lua_Number)ni;
960 luaL_argcheck(L, -1 < diff && diff < 1, arg,
961 "not a non-negative number in proper range");
962 addlenmod(form, LUA_INTFRMLEN);
963 nb = str_sprintf(buff, form, ni);
966 #if defined(LUA_USE_FLOAT_FORMATS)
967 case 'e': case 'E': case 'f':
968 #if defined(LUA_USE_AFORMAT)
971 case 'g': case 'G': {
972 addlenmod(form, LUA_FLTFRMLEN);
973 nb = str_sprintf(buff, form, (LUA_FLTFRM_T)luaL_checknumber(L, arg));
978 addquoted(L, &b, arg);
983 const char *s = luaL_tolstring(L, arg, &l);
984 if (!strchr(form, '.') && l >= 100) {
985 /* no precision and string is too long to be formatted;
986 keep original string */
991 nb = str_sprintf(buff, form, s);
992 lua_pop(L, 1); /* remove result from 'luaL_tolstring' */
996 default: { /* also treat cases `pnLlh' */
997 return luaL_error(L, "invalid option " LUA_QL("%%%c") " to "
998 LUA_QL("format"), *(strfrmt - 1));
1001 luaL_addsize(&b, nb);
1004 luaL_pushresult(&b);
1008 /* }====================================================== */
1011 static const luaL_Reg strlib[] = {
1016 {"format", str_format},
1017 {"gmatch", str_gmatch},
1020 {"lower", str_lower},
1021 {"match", str_match},
1023 {"reverse", str_reverse},
1025 {"upper", str_upper},
1030 static void createmetatable (lua_State *L) {
1031 lua_createtable(L, 0, 1); /* table to be metatable for strings */
1032 lua_pushliteral(L, ""); /* dummy string */
1033 lua_pushvalue(L, -2); /* copy table */
1034 lua_setmetatable(L, -2); /* set table as metatable for strings */
1035 lua_pop(L, 1); /* pop dummy string */
1036 lua_pushvalue(L, -2); /* get string library */
1037 lua_setfield(L, -2, "__index"); /* metatable.__index = string */
1038 lua_pop(L, 1); /* pop metatable */
1043 ** Open string library
1045 LUAMOD_API int luaopen_string (lua_State *L) {
1046 luaL_newlib(L, strlib);