3 ** $Id: lstrlib.c,v 1.178.1.1 2013/04/12 18:48:47 roberto Exp $
4 ** Standard library for string operations and pattern-matching
5 ** See Copyright Notice in lua.h
12 #include <sys/lua/lua.h>
14 #include <sys/lua/lauxlib.h>
15 #include <sys/lua/lualib.h>
19 ** maximum number of captures that a pattern can do during
20 ** pattern-matching. This limit is arbitrary.
22 #if !defined(LUA_MAXCAPTURES)
23 #define LUA_MAXCAPTURES 16
27 /* macro to `unsign' a character */
28 #define uchar(c) ((unsigned char)(c))
31 * The provided version of sprintf returns a char *, but str_format expects
32 * it to return the number of characters printed. This version has the expected
35 static size_t str_sprintf(char *buf, const char *fmt, ...) {
40 len = vsnprintf(buf, INT_MAX, fmt, args);
47 static int str_len (lua_State *L) {
49 luaL_checklstring(L, 1, &l);
50 lua_pushinteger(L, (lua_Integer)l);
55 /* translate a relative string position: negative means back from end */
56 static size_t posrelat (ptrdiff_t pos, size_t len) {
57 if (pos >= 0) return (size_t)pos;
58 else if (0u - (size_t)pos > len) return 0;
59 else return len - ((size_t)-pos) + 1;
63 static int str_sub (lua_State *L) {
65 const char *s = luaL_checklstring(L, 1, &l);
66 size_t start = posrelat(luaL_checkinteger(L, 2), l);
67 size_t end = posrelat(luaL_optinteger(L, 3, -1), l);
68 if (start < 1) start = 1;
71 lua_pushlstring(L, s + start - 1, end - start + 1);
72 else lua_pushliteral(L, "");
77 static int str_reverse (lua_State *L) {
80 const char *s = luaL_checklstring(L, 1, &l);
81 char *p = luaL_buffinitsize(L, &b, l);
82 for (i = 0; i < l; i++)
84 luaL_pushresultsize(&b, l);
89 static int str_lower (lua_State *L) {
93 const char *s = luaL_checklstring(L, 1, &l);
94 char *p = luaL_buffinitsize(L, &b, l);
96 p[i] = tolower(uchar(s[i]));
97 luaL_pushresultsize(&b, l);
102 static int str_upper (lua_State *L) {
106 const char *s = luaL_checklstring(L, 1, &l);
107 char *p = luaL_buffinitsize(L, &b, l);
109 p[i] = toupper(uchar(s[i]));
110 luaL_pushresultsize(&b, l);
115 /* reasonable limit to avoid arithmetic overflow */
116 #define MAXSIZE ((~(size_t)0) >> 1)
118 static int str_rep (lua_State *L) {
120 const char *s = luaL_checklstring(L, 1, &l);
121 int n = luaL_checkint(L, 2);
122 const char *sep = luaL_optlstring(L, 3, "", &lsep);
123 if (n <= 0) lua_pushliteral(L, "");
124 else if (l + lsep < l || l + lsep >= MAXSIZE / n) /* may overflow? */
125 return luaL_error(L, "resulting string too large");
127 size_t totallen = n * l + (n - 1) * lsep;
129 char *p = luaL_buffinitsize(L, &b, totallen);
130 while (n-- > 1) { /* first n-1 copies (followed by separator) */
131 memcpy(p, s, l * sizeof(char)); p += l;
132 if (lsep > 0) { /* avoid empty 'memcpy' (may be expensive) */
133 memcpy(p, sep, lsep * sizeof(char)); p += lsep;
136 memcpy(p, s, l * sizeof(char)); /* last copy (not followed by separator) */
137 luaL_pushresultsize(&b, totallen);
143 static int str_byte (lua_State *L) {
145 const char *s = luaL_checklstring(L, 1, &l);
146 size_t posi = posrelat(luaL_optinteger(L, 2, 1), l);
147 size_t pose = posrelat(luaL_optinteger(L, 3, posi), l);
149 if (posi < 1) posi = 1;
150 if (pose > l) pose = l;
151 if (posi > pose) return 0; /* empty interval; return no values */
152 n = (int)(pose - posi + 1);
153 if (posi + n <= pose) /* (size_t -> int) overflow? */
154 return luaL_error(L, "string slice too long");
155 luaL_checkstack(L, n, "string slice too long");
157 lua_pushinteger(L, uchar(s[posi+i-1]));
162 static int str_char (lua_State *L) {
163 int n = lua_gettop(L); /* number of arguments */
166 char *p = luaL_buffinitsize(L, &b, n);
167 for (i=1; i<=n; i++) {
168 int c = luaL_checkint(L, i);
169 luaL_argcheck(L, uchar(c) == c, i, "value out of range");
172 luaL_pushresultsize(&b, n);
177 #if defined(LUA_USE_DUMP)
178 static int writer (lua_State *L, const void* b, size_t size, void* B) {
180 luaL_addlstring((luaL_Buffer*) B, (const char *)b, size);
185 static int str_dump (lua_State *L) {
187 luaL_checktype(L, 1, LUA_TFUNCTION);
190 if (lua_dump(L, writer, &b) != 0)
191 return luaL_error(L, "unable to dump given function");
199 ** {======================================================
201 ** =======================================================
205 #define CAP_UNFINISHED (-1)
206 #define CAP_POSITION (-2)
209 typedef struct MatchState {
210 int matchdepth; /* control for recursive depth (to avoid C stack overflow) */
211 const char *src_init; /* init of source string */
212 const char *src_end; /* end ('\0') of source string */
213 const char *p_end; /* end ('\0') of pattern */
215 int level; /* total number of captures (finished or unfinished) */
219 } capture[LUA_MAXCAPTURES];
223 /* recursive function */
224 static const char *match (MatchState *ms, const char *s, const char *p);
227 /* maximum recursion depth for 'match' */
228 #if !defined(MAXCCALLS)
229 #define MAXCCALLS 200
234 #define SPECIALS "^$*+?.([%-"
237 static int check_capture (MatchState *ms, int l) {
239 if (l < 0 || l >= ms->level || ms->capture[l].len == CAP_UNFINISHED)
240 return luaL_error(ms->L, "invalid capture index %%%d", l + 1);
245 static int capture_to_close (MatchState *ms) {
246 int level = ms->level;
247 for (level--; level>=0; level--)
248 if (ms->capture[level].len == CAP_UNFINISHED) return level;
249 return luaL_error(ms->L, "invalid pattern capture");
253 static const char *classend (MatchState *ms, const char *p) {
257 luaL_error(ms->L, "malformed pattern (ends with " LUA_QL("%%") ")");
262 do { /* look for a `]' */
264 luaL_error(ms->L, "malformed pattern (missing " LUA_QL("]") ")");
265 if (*(p++) == L_ESC && p < ms->p_end)
266 p++; /* skip escapes (e.g. `%]') */
277 static int match_class (int c, int cl) {
279 switch (tolower(cl)) {
280 case 'a' : res = isalpha(c); break;
281 case 'c' : res = iscntrl(c); break;
282 case 'd' : res = isdigit(c); break;
283 case 'g' : res = isgraph(c); break;
284 case 'l' : res = islower(c); break;
285 case 'p' : res = ispunct(c); break;
286 case 's' : res = isspace(c); break;
287 case 'u' : res = isupper(c); break;
288 case 'w' : res = isalnum(c); break;
289 case 'x' : res = isxdigit(c); break;
290 case 'z' : res = (c == 0); break; /* deprecated option */
291 default: return (cl == c);
293 return (islower(cl) ? res : !res);
297 static int matchbracketclass (int c, const char *p, const char *ec) {
301 p++; /* skip the `^' */
306 if (match_class(c, uchar(*p)))
309 else if ((*(p+1) == '-') && (p+2 < ec)) {
311 if (uchar(*(p-2)) <= c && c <= uchar(*p))
314 else if (uchar(*p) == c) return sig;
320 static int singlematch (MatchState *ms, const char *s, const char *p,
322 if (s >= ms->src_end)
327 case '.': return 1; /* matches any char */
328 case L_ESC: return match_class(c, uchar(*(p+1)));
329 case '[': return matchbracketclass(c, p, ep-1);
330 default: return (uchar(*p) == c);
336 static const char *matchbalance (MatchState *ms, const char *s,
338 if (p >= ms->p_end - 1)
339 luaL_error(ms->L, "malformed pattern "
340 "(missing arguments to " LUA_QL("%%b") ")");
341 if (*s != *p) return NULL;
346 while (++s < ms->src_end) {
348 if (--cont == 0) return s+1;
350 else if (*s == b) cont++;
353 return NULL; /* string ends out of balance */
357 static const char *max_expand (MatchState *ms, const char *s,
358 const char *p, const char *ep) {
359 ptrdiff_t i = 0; /* counts maximum expand for item */
360 while (singlematch(ms, s + i, p, ep))
362 /* keeps trying to match with the maximum repetitions */
364 const char *res = match(ms, (s+i), ep+1);
366 i--; /* else didn't match; reduce 1 repetition to try again */
372 static const char *min_expand (MatchState *ms, const char *s,
373 const char *p, const char *ep) {
375 const char *res = match(ms, s, ep+1);
378 else if (singlematch(ms, s, p, ep))
379 s++; /* try with one more repetition */
385 static const char *start_capture (MatchState *ms, const char *s,
386 const char *p, int what) {
388 int level = ms->level;
389 if (level >= LUA_MAXCAPTURES) luaL_error(ms->L, "too many captures");
390 ms->capture[level].init = s;
391 ms->capture[level].len = what;
393 if ((res=match(ms, s, p)) == NULL) /* match failed? */
394 ms->level--; /* undo capture */
399 static const char *end_capture (MatchState *ms, const char *s,
401 int l = capture_to_close(ms);
403 ms->capture[l].len = s - ms->capture[l].init; /* close capture */
404 if ((res = match(ms, s, p)) == NULL) /* match failed? */
405 ms->capture[l].len = CAP_UNFINISHED; /* undo capture */
410 static const char *match_capture (MatchState *ms, const char *s, int l) {
412 l = check_capture(ms, l);
413 len = ms->capture[l].len;
414 if ((size_t)(ms->src_end-s) >= len &&
415 memcmp(ms->capture[l].init, s, len) == 0)
421 static const char *match (MatchState *ms, const char *s, const char *p) {
422 if (ms->matchdepth-- == 0)
423 luaL_error(ms->L, "pattern too complex");
424 init: /* using goto's to optimize tail recursion */
425 if (p != ms->p_end) { /* end of pattern? */
427 case '(': { /* start capture */
428 if (*(p + 1) == ')') /* position capture? */
429 s = start_capture(ms, s, p + 2, CAP_POSITION);
431 s = start_capture(ms, s, p + 1, CAP_UNFINISHED);
434 case ')': { /* end capture */
435 s = end_capture(ms, s, p + 1);
439 if ((p + 1) != ms->p_end) /* is the `$' the last char in pattern? */
440 goto dflt; /* no; go to default */
441 s = (s == ms->src_end) ? s : NULL; /* check end of string */
444 case L_ESC: { /* escaped sequences not in the format class[*+?-]? */
446 case 'b': { /* balanced string? */
447 s = matchbalance(ms, s, p + 2);
449 p += 4; goto init; /* return match(ms, s, p + 4); */
450 } /* else fail (s == NULL) */
453 case 'f': { /* frontier? */
454 const char *ep; char previous;
457 luaL_error(ms->L, "missing " LUA_QL("[") " after "
458 LUA_QL("%%f") " in pattern");
459 ep = classend(ms, p); /* points to what is next */
460 previous = (s == ms->src_init) ? '\0' : *(s - 1);
461 if (!matchbracketclass(uchar(previous), p, ep - 1) &&
462 matchbracketclass(uchar(*s), p, ep - 1)) {
463 p = ep; goto init; /* return match(ms, s, ep); */
465 s = NULL; /* match failed */
468 case '0': case '1': case '2': case '3':
469 case '4': case '5': case '6': case '7':
470 case '8': case '9': { /* capture results (%0-%9)? */
471 s = match_capture(ms, s, uchar(*(p + 1)));
473 p += 2; goto init; /* return match(ms, s, p + 2) */
481 default: dflt: { /* pattern class plus optional suffix */
482 const char *ep = classend(ms, p); /* points to optional suffix */
483 /* does not match at least once? */
484 if (!singlematch(ms, s, p, ep)) {
485 if (*ep == '*' || *ep == '?' || *ep == '-') { /* accept empty? */
486 p = ep + 1; goto init; /* return match(ms, s, ep + 1); */
488 else /* '+' or no suffix */
491 else { /* matched once */
492 switch (*ep) { /* handle optional suffix */
493 case '?': { /* optional */
495 if ((res = match(ms, s + 1, ep + 1)) != NULL)
498 p = ep + 1; goto init; /* else return match(ms, s, ep + 1); */
502 case '+': /* 1 or more repetitions */
503 s++; /* 1 match already done */
505 case '*': /* 0 or more repetitions */
506 s = max_expand(ms, s, p, ep);
508 case '-': /* 0 or more repetitions (minimum) */
509 s = min_expand(ms, s, p, ep);
511 default: /* no suffix */
512 s++; p = ep; goto init; /* return match(ms, s + 1, ep); */
525 static const char *lmemfind (const char *s1, size_t l1,
526 const char *s2, size_t l2) {
527 if (l2 == 0) return s1; /* empty strings are everywhere */
528 else if (l2 > l1) return NULL; /* avoids a negative `l1' */
530 const char *init; /* to search for a `*s2' inside `s1' */
531 l2--; /* 1st char will be checked by `memchr' */
532 l1 = l1-l2; /* `s2' cannot be found after that */
533 while (l1 > 0 && (init = (const char *)memchr(s1, *s2, l1)) != NULL) {
534 init++; /* 1st char is already checked */
535 if (memcmp(init, s2+1, l2) == 0)
537 else { /* correct `l1' and `s1' to try again */
542 return NULL; /* not found */
547 static void push_onecapture (MatchState *ms, int i, const char *s,
549 if (i >= ms->level) {
550 if (i == 0) /* ms->level == 0, too */
551 lua_pushlstring(ms->L, s, e - s); /* add whole match */
553 luaL_error(ms->L, "invalid capture index");
556 ptrdiff_t l = ms->capture[i].len;
557 if (l == CAP_UNFINISHED) luaL_error(ms->L, "unfinished capture");
558 if (l == CAP_POSITION)
559 lua_pushinteger(ms->L, ms->capture[i].init - ms->src_init + 1);
561 lua_pushlstring(ms->L, ms->capture[i].init, l);
566 static int push_captures (MatchState *ms, const char *s, const char *e) {
568 int nlevels = (ms->level == 0 && s) ? 1 : ms->level;
569 luaL_checkstack(ms->L, nlevels, "too many captures");
570 for (i = 0; i < nlevels; i++)
571 push_onecapture(ms, i, s, e);
572 return nlevels; /* number of strings pushed */
576 /* check whether pattern has no special characters */
577 static int nospecials (const char *p, size_t l) {
580 if (strpbrk(p + upto, SPECIALS))
581 return 0; /* pattern has a special character */
582 upto += strlen(p + upto) + 1; /* may have more after \0 */
584 return 1; /* no special chars found */
588 static int str_find_aux (lua_State *L, int find) {
590 const char *s = luaL_checklstring(L, 1, &ls);
591 const char *p = luaL_checklstring(L, 2, &lp);
592 size_t init = posrelat(luaL_optinteger(L, 3, 1), ls);
593 if (init < 1) init = 1;
594 else if (init > ls + 1) { /* start after string's end? */
595 lua_pushnil(L); /* cannot find anything */
598 /* explicit request or no special characters? */
599 if (find && (lua_toboolean(L, 4) || nospecials(p, lp))) {
600 /* do a plain search */
601 const char *s2 = lmemfind(s + init - 1, ls - init + 1, p, lp);
603 lua_pushinteger(L, s2 - s + 1);
604 lua_pushinteger(L, s2 - s + lp);
610 const char *s1 = s + init - 1;
611 int anchor = (*p == '^');
613 p++; lp--; /* skip anchor character */
616 ms.matchdepth = MAXCCALLS;
623 lua_assert(ms.matchdepth == MAXCCALLS);
624 if ((res=match(&ms, s1, p)) != NULL) {
626 lua_pushinteger(L, s1 - s + 1); /* start */
627 lua_pushinteger(L, res - s); /* end */
628 return push_captures(&ms, NULL, 0) + 2;
631 return push_captures(&ms, s1, res);
633 } while (s1++ < ms.src_end && !anchor);
635 lua_pushnil(L); /* not found */
640 static int str_find (lua_State *L) {
641 return str_find_aux(L, 1);
645 static int str_match (lua_State *L) {
646 return str_find_aux(L, 0);
650 static int gmatch_aux (lua_State *L) {
653 const char *s = lua_tolstring(L, lua_upvalueindex(1), &ls);
654 const char *p = lua_tolstring(L, lua_upvalueindex(2), &lp);
657 ms.matchdepth = MAXCCALLS;
661 for (src = s + (size_t)lua_tointeger(L, lua_upvalueindex(3));
666 lua_assert(ms.matchdepth == MAXCCALLS);
667 if ((e = match(&ms, src, p)) != NULL) {
668 lua_Integer newstart = e-s;
669 if (e == src) newstart++; /* empty match? go at least one position */
670 lua_pushinteger(L, newstart);
671 lua_replace(L, lua_upvalueindex(3));
672 return push_captures(&ms, src, e);
675 return 0; /* not found */
679 static int str_gmatch (lua_State *L) {
680 luaL_checkstring(L, 1);
681 luaL_checkstring(L, 2);
683 lua_pushinteger(L, 0);
684 lua_pushcclosure(L, gmatch_aux, 3);
689 static void add_s (MatchState *ms, luaL_Buffer *b, const char *s,
692 const char *news = lua_tolstring(ms->L, 3, &l);
693 for (i = 0; i < l; i++) {
694 if (news[i] != L_ESC)
695 luaL_addchar(b, news[i]);
698 if (!isdigit(uchar(news[i]))) {
699 if (news[i] != L_ESC)
700 luaL_error(ms->L, "invalid use of " LUA_QL("%c")
701 " in replacement string", L_ESC);
702 luaL_addchar(b, news[i]);
704 else if (news[i] == '0')
705 luaL_addlstring(b, s, e - s);
707 push_onecapture(ms, news[i] - '1', s, e);
708 luaL_addvalue(b); /* add capture to accumulated result */
715 static void add_value (MatchState *ms, luaL_Buffer *b, const char *s,
716 const char *e, int tr) {
717 lua_State *L = ms->L;
719 case LUA_TFUNCTION: {
722 n = push_captures(ms, s, e);
727 push_onecapture(ms, 0, s, e);
731 default: { /* LUA_TNUMBER or LUA_TSTRING */
736 if (!lua_toboolean(L, -1)) { /* nil or false? */
738 lua_pushlstring(L, s, e - s); /* keep original text */
740 else if (!lua_isstring(L, -1))
741 luaL_error(L, "invalid replacement value (a %s)", luaL_typename(L, -1));
742 luaL_addvalue(b); /* add result to accumulator */
746 static int str_gsub (lua_State *L) {
748 const char *src = luaL_checklstring(L, 1, &srcl);
749 const char *p = luaL_checklstring(L, 2, &lp);
750 int tr = lua_type(L, 3);
751 size_t max_s = luaL_optinteger(L, 4, srcl+1);
752 int anchor = (*p == '^');
756 luaL_argcheck(L, tr == LUA_TNUMBER || tr == LUA_TSTRING ||
757 tr == LUA_TFUNCTION || tr == LUA_TTABLE, 3,
758 "string/function/table expected");
759 luaL_buffinit(L, &b);
761 p++; lp--; /* skip anchor character */
764 ms.matchdepth = MAXCCALLS;
766 ms.src_end = src+srcl;
771 lua_assert(ms.matchdepth == MAXCCALLS);
772 e = match(&ms, src, p);
775 add_value(&ms, &b, src, e, tr);
777 if (e && e>src) /* non empty match? */
778 src = e; /* skip it */
779 else if (src < ms.src_end)
780 luaL_addchar(&b, *src++);
784 luaL_addlstring(&b, src, ms.src_end-src);
786 lua_pushinteger(L, n); /* number of substitutions */
790 /* }====================================================== */
795 ** {======================================================
797 ** =======================================================
801 ** LUA_INTFRMLEN is the length modifier for integer conversions in
802 ** 'string.format'; LUA_INTFRM_T is the integer type corresponding to
803 ** the previous length
805 #if !defined(LUA_INTFRMLEN) /* { */
806 #if defined(LUA_USE_LONGLONG)
808 #define LUA_INTFRMLEN "ll"
809 #define LUA_INTFRM_T long long
813 #define LUA_INTFRMLEN "l"
814 #define LUA_INTFRM_T long
821 ** LUA_FLTFRMLEN is the length modifier for float conversions in
822 ** 'string.format'; LUA_FLTFRM_T is the float type corresponding to
823 ** the previous length
825 #if !defined(LUA_FLTFRMLEN)
827 #define LUA_FLTFRMLEN ""
828 #define LUA_FLTFRM_T double
833 /* maximum size of each formatted item (> len(format('%99.99f', -1e308))) */
835 /* valid flags in a format specification */
836 #define FLAGS "-+ #0"
838 ** maximum size of each format specification (such as '%-099.99d')
839 ** (+10 accounts for %99.99x plus margin of error)
841 #define MAX_FORMAT (sizeof(FLAGS) + sizeof(LUA_INTFRMLEN) + 10)
844 static void addquoted (lua_State *L, luaL_Buffer *b, int arg) {
846 const char *s = luaL_checklstring(L, arg, &l);
847 luaL_addchar(b, '"');
849 if (*s == '"' || *s == '\\' || *s == '\n') {
850 luaL_addchar(b, '\\');
853 else if (*s == '\0' || iscntrl(uchar(*s))) {
855 if (!isdigit(uchar(*(s+1))))
856 snprintf(buff, sizeof(buff), "\\%d", (int)uchar(*s));
858 snprintf(buff, sizeof(buff), "\\%03d", (int)uchar(*s));
859 luaL_addstring(b, buff);
865 luaL_addchar(b, '"');
868 static const char *scanformat (lua_State *L, const char *strfrmt, char *form) {
869 const char *p = strfrmt;
870 while (*p != '\0' && strchr(FLAGS, *p) != NULL) p++; /* skip flags */
871 if ((size_t)(p - strfrmt) >= sizeof(FLAGS)/sizeof(char))
872 luaL_error(L, "invalid format (repeated flags)");
873 if (isdigit(uchar(*p))) p++; /* skip width */
874 if (isdigit(uchar(*p))) p++; /* (2 digits at most) */
877 if (isdigit(uchar(*p))) p++; /* skip precision */
878 if (isdigit(uchar(*p))) p++; /* (2 digits at most) */
880 if (isdigit(uchar(*p)))
881 luaL_error(L, "invalid format (width or precision too long)");
883 memcpy(form, strfrmt, (p - strfrmt + 1) * sizeof(char));
884 form += p - strfrmt + 1;
891 ** add length modifier into formats
893 static void addlenmod (char *form, const char *lenmod, size_t size) {
894 size_t l = strlen(form);
895 size_t lm = strlen(lenmod);
896 char spec = form[l - 1];
897 strlcpy(form + l - 1, lenmod, size - (l - 1));
898 form[l + lm - 1] = spec;
903 static int str_format (lua_State *L) {
904 int top = lua_gettop(L);
907 const char *strfrmt = luaL_checklstring(L, arg, &sfl);
908 const char *strfrmt_end = strfrmt+sfl;
910 luaL_buffinit(L, &b);
911 while (strfrmt < strfrmt_end) {
912 if (*strfrmt != L_ESC)
913 luaL_addchar(&b, *strfrmt++);
914 else if (*++strfrmt == L_ESC)
915 luaL_addchar(&b, *strfrmt++); /* %% */
916 else { /* format item */
917 char form[MAX_FORMAT]; /* to store the format (`%...') */
918 char *buff = luaL_prepbuffsize(&b, MAX_ITEM); /* to put formatted item */
919 int nb = 0; /* number of bytes in added item */
921 luaL_argerror(L, arg, "no value");
922 strfrmt = scanformat(L, strfrmt, form);
923 switch (*strfrmt++) {
925 nb = str_sprintf(buff, form, luaL_checkint(L, arg));
928 case 'd': case 'i': {
929 lua_Number n = luaL_checknumber(L, arg);
930 LUA_INTFRM_T ni = (LUA_INTFRM_T)n;
931 lua_Number diff = n - (lua_Number)ni;
932 luaL_argcheck(L, -1 < diff && diff < 1, arg,
933 "not a number in proper range");
934 addlenmod(form, LUA_INTFRMLEN, MAX_FORMAT);
935 nb = str_sprintf(buff, form, ni);
938 case 'o': case 'u': case 'x': case 'X': {
939 lua_Number n = luaL_checknumber(L, arg);
940 unsigned LUA_INTFRM_T ni = (unsigned LUA_INTFRM_T)n;
941 lua_Number diff = n - (lua_Number)ni;
942 luaL_argcheck(L, -1 < diff && diff < 1, arg,
943 "not a non-negative number in proper range");
944 addlenmod(form, LUA_INTFRMLEN, MAX_FORMAT);
945 nb = str_sprintf(buff, form, ni);
948 #if defined(LUA_USE_FLOAT_FORMATS)
949 case 'e': case 'E': case 'f':
950 #if defined(LUA_USE_AFORMAT)
953 case 'g': case 'G': {
954 addlenmod(form, LUA_FLTFRMLEN, MAX_FORMAT);
955 nb = str_sprintf(buff, form, (LUA_FLTFRM_T)luaL_checknumber(L, arg));
960 addquoted(L, &b, arg);
965 const char *s = luaL_tolstring(L, arg, &l);
966 if (!strchr(form, '.') && l >= 100) {
967 /* no precision and string is too long to be formatted;
968 keep original string */
973 nb = str_sprintf(buff, form, s);
974 lua_pop(L, 1); /* remove result from 'luaL_tolstring' */
978 default: { /* also treat cases `pnLlh' */
979 return luaL_error(L, "invalid option " LUA_QL("%%%c") " to "
980 LUA_QL("format"), *(strfrmt - 1));
983 luaL_addsize(&b, nb);
990 /* }====================================================== */
993 static const luaL_Reg strlib[] = {
996 #if defined(LUA_USE_DUMP)
1000 {"format", str_format},
1001 {"gmatch", str_gmatch},
1004 {"lower", str_lower},
1005 {"match", str_match},
1007 {"reverse", str_reverse},
1009 {"upper", str_upper},
1014 static void createmetatable (lua_State *L) {
1015 lua_createtable(L, 0, 1); /* table to be metatable for strings */
1016 lua_pushliteral(L, ""); /* dummy string */
1017 lua_pushvalue(L, -2); /* copy table */
1018 lua_setmetatable(L, -2); /* set table as metatable for strings */
1019 lua_pop(L, 1); /* pop dummy string */
1020 lua_pushvalue(L, -2); /* get string library */
1021 lua_setfield(L, -2, "__index"); /* metatable.__index = string */
1022 lua_pop(L, 1); /* pop metatable */
1027 ** Open string library
1029 LUAMOD_API int luaopen_string (lua_State *L) {
1030 luaL_newlib(L, strlib);
1035 #if defined(_KERNEL)
1037 EXPORT_SYMBOL(luaopen_string);