2 ** $Id: lstrlib.c,v 1.178 2012/08/14 18:12:34 roberto Exp $
3 ** Standard library for string operations and pattern-matching
4 ** See Copyright Notice in lua.h
24 ** maximum number of captures that a pattern can do during
25 ** pattern-matching. This limit is arbitrary.
27 #if !defined(LUA_MAXCAPTURES)
28 #define LUA_MAXCAPTURES 32
32 /* macro to `unsign' a character */
33 #define uchar(c) ((unsigned char)(c))
37 static int str_len(lua_State
*L
) {
39 luaL_checklstring(L
, 1, &l
);
40 lua_pushinteger(L
, (lua_Integer
)l
);
45 /* translate a relative string position: negative means back from end */
46 static size_t posrelat(ptrdiff_t pos
, size_t len
) {
47 if (pos
>= 0) return (size_t)pos
;
48 else if (0u - (size_t)pos
> len
) return 0;
49 else return len
- ((size_t) - pos
) + 1;
53 static int str_sub(lua_State
*L
) {
55 const char *s
= luaL_checklstring(L
, 1, &l
);
56 size_t start
= posrelat(luaL_checkinteger(L
, 2), l
);
57 size_t end
= posrelat(luaL_optinteger(L
, 3, -1), l
);
58 if (start
< 1) start
= 1;
61 lua_pushlstring(L
, s
+ start
- 1, end
- start
+ 1);
62 else lua_pushliteral(L
, "");
67 static int str_reverse(lua_State
*L
) {
70 const char *s
= luaL_checklstring(L
, 1, &l
);
71 char *p
= luaL_buffinitsize(L
, &b
, l
);
72 for (i
= 0; i
< l
; i
++)
74 luaL_pushresultsize(&b
, l
);
79 static int str_lower(lua_State
*L
) {
83 const char *s
= luaL_checklstring(L
, 1, &l
);
84 char *p
= luaL_buffinitsize(L
, &b
, l
);
85 for (i
= 0; i
< l
; i
++)
86 p
[i
] = tolower(uchar(s
[i
]));
87 luaL_pushresultsize(&b
, l
);
92 static int str_upper(lua_State
*L
) {
96 const char *s
= luaL_checklstring(L
, 1, &l
);
97 char *p
= luaL_buffinitsize(L
, &b
, l
);
98 for (i
= 0; i
< l
; i
++)
99 p
[i
] = toupper(uchar(s
[i
]));
100 luaL_pushresultsize(&b
, l
);
105 /* reasonable limit to avoid arithmetic overflow */
106 #define MAXSIZE ((~(size_t)0) >> 1)
108 static int str_rep(lua_State
*L
) {
110 const char *s
= luaL_checklstring(L
, 1, &l
);
111 int n
= luaL_checkint(L
, 2);
112 const char *sep
= luaL_optlstring(L
, 3, "", &lsep
);
113 if (n
<= 0) lua_pushliteral(L
, "");
114 else if (l
+ lsep
< l
|| l
+ lsep
>= MAXSIZE
/ n
) /* may overflow? */
115 return luaL_error(L
, "resulting string too large");
117 size_t totallen
= n
* l
+ (n
- 1) * lsep
;
119 char *p
= luaL_buffinitsize(L
, &b
, totallen
);
120 while (n
-- > 1) { /* first n-1 copies (followed by separator) */
121 memcpy(p
, s
, l
* sizeof(char));
123 if (lsep
> 0) { /* avoid empty 'memcpy' (may be expensive) */
124 memcpy(p
, sep
, lsep
* sizeof(char));
128 memcpy(p
, s
, l
* sizeof(char)); /* last copy (not followed by separator) */
129 luaL_pushresultsize(&b
, totallen
);
135 static int str_byte(lua_State
*L
) {
137 const char *s
= luaL_checklstring(L
, 1, &l
);
138 size_t posi
= posrelat(luaL_optinteger(L
, 2, 1), l
);
139 size_t pose
= posrelat(luaL_optinteger(L
, 3, posi
), l
);
141 if (posi
< 1) posi
= 1;
142 if (pose
> l
) pose
= l
;
143 if (posi
> pose
) return 0; /* empty interval; return no values */
144 n
= (int)(pose
- posi
+ 1);
145 if (posi
+ n
<= pose
) /* (size_t -> int) overflow? */
146 return luaL_error(L
, "string slice too long");
147 luaL_checkstack(L
, n
, "string slice too long");
148 for (i
= 0; i
< n
; i
++)
149 lua_pushinteger(L
, uchar(s
[posi
+ i
- 1]));
154 static int str_char(lua_State
*L
) {
155 int n
= lua_gettop(L
); /* number of arguments */
158 char *p
= luaL_buffinitsize(L
, &b
, n
);
159 for (i
= 1; i
<= n
; i
++) {
160 int c
= luaL_checkint(L
, i
);
161 luaL_argcheck(L
, uchar(c
) == c
, i
, "value out of range");
164 luaL_pushresultsize(&b
, n
);
169 static int writer(lua_State
*L
, const void *b
, size_t size
, void *B
) {
171 luaL_addlstring((luaL_Buffer
*) B
, (const char *)b
, size
);
176 static int str_dump(lua_State
*L
) {
178 luaL_checktype(L
, 1, LUA_TFUNCTION
);
180 luaL_buffinit(L
, &b
);
181 if (lua_dump(L
, writer
, &b
) != 0)
182 return luaL_error(L
, "unable to dump given function");
190 ** {======================================================
192 ** =======================================================
196 #define CAP_UNFINISHED (-1)
197 #define CAP_POSITION (-2)
200 typedef struct MatchState
{
201 int matchdepth
; /* control for recursive depth (to avoid C stack overflow) */
202 const char *src_init
; /* init of source string */
203 const char *src_end
; /* end ('\0') of source string */
204 const char *p_end
; /* end ('\0') of pattern */
206 int level
; /* total number of captures (finished or unfinished) */
210 } capture
[LUA_MAXCAPTURES
];
214 /* recursive function */
215 static const char *match(MatchState
*ms
, const char *s
, const char *p
);
218 /* maximum recursion depth for 'match' */
219 #if !defined(MAXCCALLS)
220 #define MAXCCALLS 200
225 #define SPECIALS "^$*+?.([%-"
228 static int check_capture(MatchState
*ms
, int l
) {
230 if (l
< 0 || l
>= ms
->level
|| ms
->capture
[l
].len
== CAP_UNFINISHED
)
231 return luaL_error(ms
->L
, "invalid capture index %%%d", l
+ 1);
236 static int capture_to_close(MatchState
*ms
) {
237 int level
= ms
->level
;
238 for (level
--; level
>= 0; level
--)
239 if (ms
->capture
[level
].len
== CAP_UNFINISHED
) return level
;
240 return luaL_error(ms
->L
, "invalid pattern capture");
244 static const char *classend(MatchState
*ms
, const char *p
) {
248 luaL_error(ms
->L
, "malformed pattern (ends with " LUA_QL("%%") ")");
253 do { /* look for a `]' */
255 luaL_error(ms
->L
, "malformed pattern (missing " LUA_QL("]") ")");
256 if (*(p
++) == L_ESC
&& p
< ms
->p_end
)
257 p
++; /* skip escapes (e.g. `%]') */
268 static int match_class(int c
, int cl
) {
270 switch (tolower(cl
)) {
303 break; /* deprecated option */
307 return (islower(cl
) ? res
: !res
);
311 static int matchbracketclass(int c
, const char *p
, const char *ec
) {
313 if (*(p
+ 1) == '^') {
315 p
++; /* skip the `^' */
320 if (match_class(c
, uchar(*p
)))
322 } else if ((*(p
+ 1) == '-') && (p
+ 2 < ec
)) {
324 if (uchar(*(p
- 2)) <= c
&& c
<= uchar(*p
))
326 } else if (uchar(*p
) == c
) return sig
;
332 static int singlematch(MatchState
*ms
, const char *s
, const char *p
,
334 if (s
>= ms
->src_end
)
340 return 1; /* matches any char */
342 return match_class(c
, uchar(*(p
+ 1)));
344 return matchbracketclass(c
, p
, ep
- 1);
346 return (uchar(*p
) == c
);
352 static const char *matchbalance(MatchState
*ms
, const char *s
,
354 if (p
>= ms
->p_end
- 1)
355 luaL_error(ms
->L
, "malformed pattern "
356 "(missing arguments to " LUA_QL("%%b") ")");
357 if (*s
!= *p
) return NULL
;
362 while (++s
< ms
->src_end
) {
364 if (--cont
== 0) return s
+ 1;
365 } else if (*s
== b
) cont
++;
368 return NULL
; /* string ends out of balance */
372 static const char *max_expand(MatchState
*ms
, const char *s
,
373 const char *p
, const char *ep
) {
374 ptrdiff_t i
= 0; /* counts maximum expand for item */
375 while (singlematch(ms
, s
+ i
, p
, ep
))
377 /* keeps trying to match with the maximum repetitions */
379 const char *res
= match(ms
, (s
+ i
), ep
+ 1);
381 i
--; /* else didn't match; reduce 1 repetition to try again */
387 static const char *min_expand(MatchState
*ms
, const char *s
,
388 const char *p
, const char *ep
) {
390 const char *res
= match(ms
, s
, ep
+ 1);
393 else if (singlematch(ms
, s
, p
, ep
))
394 s
++; /* try with one more repetition */
400 static const char *start_capture(MatchState
*ms
, const char *s
,
401 const char *p
, int what
) {
403 int level
= ms
->level
;
404 if (level
>= LUA_MAXCAPTURES
) luaL_error(ms
->L
, "too many captures");
405 ms
->capture
[level
].init
= s
;
406 ms
->capture
[level
].len
= what
;
407 ms
->level
= level
+ 1;
408 if ((res
= match(ms
, s
, p
)) == NULL
) /* match failed? */
409 ms
->level
--; /* undo capture */
414 static const char *end_capture(MatchState
*ms
, const char *s
,
416 int l
= capture_to_close(ms
);
418 ms
->capture
[l
].len
= s
- ms
->capture
[l
].init
; /* close capture */
419 if ((res
= match(ms
, s
, p
)) == NULL
) /* match failed? */
420 ms
->capture
[l
].len
= CAP_UNFINISHED
; /* undo capture */
425 static const char *match_capture(MatchState
*ms
, const char *s
, int l
) {
427 l
= check_capture(ms
, l
);
428 len
= ms
->capture
[l
].len
;
429 if ((size_t)(ms
->src_end
- s
) >= len
&&
430 memcmp(ms
->capture
[l
].init
, s
, len
) == 0)
436 static const char *match(MatchState
*ms
, const char *s
, const char *p
) {
437 if (ms
->matchdepth
-- == 0)
438 luaL_error(ms
->L
, "pattern too complex");
439 init
: /* using goto's to optimize tail recursion */
440 if (p
!= ms
->p_end
) { /* end of pattern? */
442 case '(': { /* start capture */
443 if (*(p
+ 1) == ')') /* position capture? */
444 s
= start_capture(ms
, s
, p
+ 2, CAP_POSITION
);
446 s
= start_capture(ms
, s
, p
+ 1, CAP_UNFINISHED
);
449 case ')': { /* end capture */
450 s
= end_capture(ms
, s
, p
+ 1);
454 if ((p
+ 1) != ms
->p_end
) /* is the `$' the last char in pattern? */
455 goto dflt
; /* no; go to default */
456 s
= (s
== ms
->src_end
) ? s
: NULL
; /* check end of string */
459 case L_ESC
: { /* escaped sequences not in the format class[*+?-]? */
461 case 'b': { /* balanced string? */
462 s
= matchbalance(ms
, s
, p
+ 2);
465 goto init
; /* return match(ms, s, p + 4); */
466 } /* else fail (s == NULL) */
469 case 'f': { /* frontier? */
474 luaL_error(ms
->L
, "missing " LUA_QL("[") " after "
475 LUA_QL("%%f") " in pattern");
476 ep
= classend(ms
, p
); /* points to what is next */
477 previous
= (s
== ms
->src_init
) ? '\0' : *(s
- 1);
478 if (!matchbracketclass(uchar(previous
), p
, ep
- 1) &&
479 matchbracketclass(uchar(*s
), p
, ep
- 1)) {
481 goto init
; /* return match(ms, s, ep); */
483 s
= NULL
; /* match failed */
495 case '9': { /* capture results (%0-%9)? */
496 s
= match_capture(ms
, s
, uchar(*(p
+ 1)));
499 goto init
; /* return match(ms, s, p + 2) */
509 dflt
: { /* pattern class plus optional suffix */
510 const char *ep
= classend(ms
, p
); /* points to optional suffix */
511 /* does not match at least once? */
512 if (!singlematch(ms
, s
, p
, ep
)) {
513 if (*ep
== '*' || *ep
== '?' || *ep
== '-') { /* accept empty? */
515 goto init
; /* return match(ms, s, ep + 1); */
516 } else /* '+' or no suffix */
518 } else { /* matched once */
519 switch (*ep
) { /* handle optional suffix */
520 case '?': { /* optional */
522 if ((res
= match(ms
, s
+ 1, ep
+ 1)) != NULL
)
526 goto init
; /* else return match(ms, s, ep + 1); */
530 case '+': /* 1 or more repetitions */
531 s
++; /* 1 match already done */
533 case '*': /* 0 or more repetitions */
534 s
= max_expand(ms
, s
, p
, ep
);
536 case '-': /* 0 or more repetitions (minimum) */
537 s
= min_expand(ms
, s
, p
, ep
);
539 default: /* no suffix */
542 goto init
; /* return match(ms, s + 1, ep); */
555 static const char *lmemfind(const char *s1
, size_t l1
,
556 const char *s2
, size_t l2
) {
557 if (l2
== 0) return s1
; /* empty strings are everywhere */
558 else if (l2
> l1
) return NULL
; /* avoids a negative `l1' */
560 const char *init
; /* to search for a `*s2' inside `s1' */
561 l2
--; /* 1st char will be checked by `memchr' */
562 l1
= l1
- l2
; /* `s2' cannot be found after that */
563 while (l1
> 0 && (init
= (const char *)memchr(s1
, *s2
, l1
)) != NULL
) {
564 init
++; /* 1st char is already checked */
565 if (memcmp(init
, s2
+ 1, l2
) == 0)
567 else { /* correct `l1' and `s1' to try again */
572 return NULL
; /* not found */
577 static void push_onecapture(MatchState
*ms
, int i
, const char *s
,
579 if (i
>= ms
->level
) {
580 if (i
== 0) /* ms->level == 0, too */
581 lua_pushlstring(ms
->L
, s
, e
- s
); /* add whole match */
583 luaL_error(ms
->L
, "invalid capture index");
585 ptrdiff_t l
= ms
->capture
[i
].len
;
586 if (l
== CAP_UNFINISHED
) luaL_error(ms
->L
, "unfinished capture");
587 if (l
== CAP_POSITION
)
588 lua_pushinteger(ms
->L
, ms
->capture
[i
].init
- ms
->src_init
+ 1);
590 lua_pushlstring(ms
->L
, ms
->capture
[i
].init
, l
);
595 static int push_captures(MatchState
*ms
, const char *s
, const char *e
) {
597 int nlevels
= (ms
->level
== 0 && s
) ? 1 : ms
->level
;
598 luaL_checkstack(ms
->L
, nlevels
, "too many captures");
599 for (i
= 0; i
< nlevels
; i
++)
600 push_onecapture(ms
, i
, s
, e
);
601 return nlevels
; /* number of strings pushed */
605 /* check whether pattern has no special characters */
606 static int nospecials(const char *p
, size_t l
) {
609 if (strpbrk(p
+ upto
, SPECIALS
))
610 return 0; /* pattern has a special character */
611 upto
+= strlen(p
+ upto
) + 1; /* may have more after \0 */
613 return 1; /* no special chars found */
617 static int str_find_aux(lua_State
*L
, int find
) {
619 const char *s
= luaL_checklstring(L
, 1, &ls
);
620 const char *p
= luaL_checklstring(L
, 2, &lp
);
621 size_t init
= posrelat(luaL_optinteger(L
, 3, 1), ls
);
622 if (init
< 1) init
= 1;
623 else if (init
> ls
+ 1) { /* start after string's end? */
624 lua_pushnil(L
); /* cannot find anything */
627 /* explicit request or no special characters? */
628 if (find
&& (lua_toboolean(L
, 4) || nospecials(p
, lp
))) {
629 /* do a plain search */
630 const char *s2
= lmemfind(s
+ init
- 1, ls
- init
+ 1, p
, lp
);
632 lua_pushinteger(L
, s2
- s
+ 1);
633 lua_pushinteger(L
, s2
- s
+ lp
);
638 const char *s1
= s
+ init
- 1;
639 int anchor
= (*p
== '^');
642 lp
--; /* skip anchor character */
645 ms
.matchdepth
= MAXCCALLS
;
652 lua_assert(ms
.matchdepth
== MAXCCALLS
);
653 if ((res
= match(&ms
, s1
, p
)) != NULL
) {
655 lua_pushinteger(L
, s1
- s
+ 1); /* start */
656 lua_pushinteger(L
, res
- s
); /* end */
657 return push_captures(&ms
, NULL
, 0) + 2;
659 return push_captures(&ms
, s1
, res
);
661 } while (s1
++ < ms
.src_end
&& !anchor
);
663 lua_pushnil(L
); /* not found */
668 static int str_find(lua_State
*L
) {
669 return str_find_aux(L
, 1);
673 static int str_match(lua_State
*L
) {
674 return str_find_aux(L
, 0);
678 static int gmatch_aux(lua_State
*L
) {
681 const char *s
= lua_tolstring(L
, lua_upvalueindex(1), &ls
);
682 const char *p
= lua_tolstring(L
, lua_upvalueindex(2), &lp
);
685 ms
.matchdepth
= MAXCCALLS
;
689 for (src
= s
+ (size_t)lua_tointeger(L
, lua_upvalueindex(3));
694 lua_assert(ms
.matchdepth
== MAXCCALLS
);
695 if ((e
= match(&ms
, src
, p
)) != NULL
) {
696 lua_Integer newstart
= e
- s
;
697 if (e
== src
) newstart
++; /* empty match? go at least one position */
698 lua_pushinteger(L
, newstart
);
699 lua_replace(L
, lua_upvalueindex(3));
700 return push_captures(&ms
, src
, e
);
703 return 0; /* not found */
707 static int gmatch(lua_State
*L
) {
708 luaL_checkstring(L
, 1);
709 luaL_checkstring(L
, 2);
711 lua_pushinteger(L
, 0);
712 lua_pushcclosure(L
, gmatch_aux
, 3);
717 static void add_s(MatchState
*ms
, luaL_Buffer
*b
, const char *s
,
720 const char *news
= lua_tolstring(ms
->L
, 3, &l
);
721 for (i
= 0; i
< l
; i
++) {
722 if (news
[i
] != L_ESC
)
723 luaL_addchar(b
, news
[i
]);
726 if (!isdigit(uchar(news
[i
]))) {
727 if (news
[i
] != L_ESC
)
728 luaL_error(ms
->L
, "invalid use of " LUA_QL("%c")
729 " in replacement string", L_ESC
);
730 luaL_addchar(b
, news
[i
]);
731 } else if (news
[i
] == '0')
732 luaL_addlstring(b
, s
, e
- s
);
734 push_onecapture(ms
, news
[i
] - '1', s
, e
);
735 luaL_addvalue(b
); /* add capture to accumulated result */
742 static void add_value(MatchState
*ms
, luaL_Buffer
*b
, const char *s
,
743 const char *e
, int tr
) {
744 lua_State
*L
= ms
->L
;
746 case LUA_TFUNCTION
: {
749 n
= push_captures(ms
, s
, e
);
754 push_onecapture(ms
, 0, s
, e
);
758 default: { /* LUA_TNUMBER or LUA_TSTRING */
763 if (!lua_toboolean(L
, -1)) { /* nil or false? */
765 lua_pushlstring(L
, s
, e
- s
); /* keep original text */
766 } else if (!lua_isstring(L
, -1))
767 luaL_error(L
, "invalid replacement value (a %s)", luaL_typename(L
, -1));
768 luaL_addvalue(b
); /* add result to accumulator */
772 static int str_gsub(lua_State
*L
) {
774 const char *src
= luaL_checklstring(L
, 1, &srcl
);
775 const char *p
= luaL_checklstring(L
, 2, &lp
);
776 int tr
= lua_type(L
, 3);
777 size_t max_s
= luaL_optinteger(L
, 4, srcl
+ 1);
778 int anchor
= (*p
== '^');
782 luaL_argcheck(L
, tr
== LUA_TNUMBER
|| tr
== LUA_TSTRING
||
783 tr
== LUA_TFUNCTION
|| tr
== LUA_TTABLE
, 3,
784 "string/function/table expected");
785 luaL_buffinit(L
, &b
);
788 lp
--; /* skip anchor character */
791 ms
.matchdepth
= MAXCCALLS
;
793 ms
.src_end
= src
+ srcl
;
798 lua_assert(ms
.matchdepth
== MAXCCALLS
);
799 e
= match(&ms
, src
, p
);
802 add_value(&ms
, &b
, src
, e
, tr
);
804 if (e
&& e
> src
) /* non empty match? */
805 src
= e
; /* skip it */
806 else if (src
< ms
.src_end
)
807 luaL_addchar(&b
, *src
++);
811 luaL_addlstring(&b
, src
, ms
.src_end
- src
);
813 lua_pushinteger(L
, n
); /* number of substitutions */
817 /* }====================================================== */
822 ** {======================================================
824 ** =======================================================
828 ** LUA_INTFRMLEN is the length modifier for integer conversions in
829 ** 'string.format'; LUA_INTFRM_T is the integer type corresponding to
830 ** the previous length
832 #if !defined(LUA_INTFRMLEN) /* { */
833 #if defined(LUA_USE_LONGLONG)
835 #define LUA_INTFRMLEN "ll"
836 #define LUA_INTFRM_T long long
840 #define LUA_INTFRMLEN "l"
841 #define LUA_INTFRM_T long
848 ** LUA_FLTFRMLEN is the length modifier for float conversions in
849 ** 'string.format'; LUA_FLTFRM_T is the float type corresponding to
850 ** the previous length
852 #if !defined(LUA_FLTFRMLEN)
854 #define LUA_FLTFRMLEN ""
855 #define LUA_FLTFRM_T double
860 /* maximum size of each formatted item (> len(format('%99.99f', -1e308))) */
862 /* valid flags in a format specification */
863 #define FLAGS "-+ #0"
865 ** maximum size of each format specification (such as '%-099.99d')
866 ** (+10 accounts for %99.99x plus margin of error)
868 #define MAX_FORMAT (sizeof(FLAGS) + sizeof(LUA_INTFRMLEN) + 10)
871 static void addquoted(lua_State
*L
, luaL_Buffer
*b
, int arg
) {
873 const char *s
= luaL_checklstring(L
, arg
, &l
);
874 luaL_addchar(b
, '"');
876 if (*s
== '"' || *s
== '\\' || *s
== '\n') {
877 luaL_addchar(b
, '\\');
879 } else if (*s
== '\0' || iscntrl(uchar(*s
))) {
881 if (!isdigit(uchar(*(s
+ 1))))
882 sprintf(buff
, "\\%d", (int)uchar(*s
));
884 sprintf(buff
, "\\%03d", (int)uchar(*s
));
885 luaL_addstring(b
, buff
);
890 luaL_addchar(b
, '"');
893 static const char *scanformat(lua_State
*L
, const char *strfrmt
, char *form
) {
894 const char *p
= strfrmt
;
895 while (*p
!= '\0' && strchr(FLAGS
, *p
) != NULL
) p
++; /* skip flags */
896 if ((size_t)(p
- strfrmt
) >= sizeof(FLAGS
) / sizeof(char))
897 luaL_error(L
, "invalid format (repeated flags)");
898 if (isdigit(uchar(*p
))) p
++; /* skip width */
899 if (isdigit(uchar(*p
))) p
++; /* (2 digits at most) */
902 if (isdigit(uchar(*p
))) p
++; /* skip precision */
903 if (isdigit(uchar(*p
))) p
++; /* (2 digits at most) */
905 if (isdigit(uchar(*p
)))
906 luaL_error(L
, "invalid format (width or precision too long)");
908 memcpy(form
, strfrmt
, (p
- strfrmt
+ 1) * sizeof(char));
909 form
+= p
- strfrmt
+ 1;
916 ** add length modifier into formats
918 static void addlenmod(char *form
, const char *lenmod
) {
919 size_t l
= strlen(form
);
920 size_t lm
= strlen(lenmod
);
921 char spec
= form
[l
- 1];
922 strcpy(form
+ l
- 1, lenmod
);
923 form
[l
+ lm
- 1] = spec
;
928 static int str_format(lua_State
*L
) {
929 int top
= lua_gettop(L
);
932 const char *strfrmt
= luaL_checklstring(L
, arg
, &sfl
);
933 const char *strfrmt_end
= strfrmt
+ sfl
;
935 luaL_buffinit(L
, &b
);
936 while (strfrmt
< strfrmt_end
) {
937 if (*strfrmt
!= L_ESC
)
938 luaL_addchar(&b
, *strfrmt
++);
939 else if (*++strfrmt
== L_ESC
)
940 luaL_addchar(&b
, *strfrmt
++); /* %% */
941 else { /* format item */
942 char form
[MAX_FORMAT
]; /* to store the format (`%...') */
943 char *buff
= luaL_prepbuffsize(&b
, MAX_ITEM
); /* to put formatted item */
944 int nb
= 0; /* number of bytes in added item */
946 luaL_argerror(L
, arg
, "no value");
947 strfrmt
= scanformat(L
, strfrmt
, form
);
948 switch (*strfrmt
++) {
950 nb
= sprintf(buff
, form
, luaL_checkint(L
, arg
));
955 lua_Number n
= luaL_checknumber(L
, arg
);
956 LUA_INTFRM_T ni
= (LUA_INTFRM_T
)n
;
957 lua_Number diff
= n
- (lua_Number
)ni
;
958 luaL_argcheck(L
, -1 < diff
&& diff
< 1, arg
,
959 "not a number in proper range");
960 addlenmod(form
, LUA_INTFRMLEN
);
961 nb
= sprintf(buff
, form
, ni
);
968 lua_Number n
= luaL_checknumber(L
, arg
);
969 unsigned LUA_INTFRM_T ni
= (unsigned LUA_INTFRM_T
)n
;
970 lua_Number diff
= n
- (lua_Number
)ni
;
971 luaL_argcheck(L
, -1 < diff
&& diff
< 1, arg
,
972 "not a non-negative number in proper range");
973 addlenmod(form
, LUA_INTFRMLEN
);
974 nb
= sprintf(buff
, form
, ni
);
980 #if defined(LUA_USE_AFORMAT)
986 addlenmod(form
, LUA_FLTFRMLEN
);
987 nb
= sprintf(buff
, form
, (LUA_FLTFRM_T
)luaL_checknumber(L
, arg
));
991 addquoted(L
, &b
, arg
);
996 const char *s
= luaL_tolstring(L
, arg
, &l
);
997 if (!strchr(form
, '.') && l
>= 100) {
998 /* no precision and string is too long to be formatted;
999 keep original string */
1003 nb
= sprintf(buff
, form
, s
);
1004 lua_pop(L
, 1); /* remove result from 'luaL_tolstring' */
1008 default: { /* also treat cases `pnLlh' */
1009 return luaL_error(L
, "invalid option " LUA_QL("%%%c") " to "
1010 LUA_QL("format"), *(strfrmt
- 1));
1013 luaL_addsize(&b
, nb
);
1016 luaL_pushresult(&b
);
1020 /* }====================================================== */
1023 static const luaL_Reg strlib
[] = {
1028 {"format", str_format
},
1032 {"lower", str_lower
},
1033 {"match", str_match
},
1035 {"reverse", str_reverse
},
1037 {"upper", str_upper
},
1042 static void createmetatable(lua_State
*L
) {
1043 lua_createtable(L
, 0, 1); /* table to be metatable for strings */
1044 lua_pushliteral(L
, ""); /* dummy string */
1045 lua_pushvalue(L
, -2); /* copy table */
1046 lua_setmetatable(L
, -2); /* set table as metatable for strings */
1047 lua_pop(L
, 1); /* pop dummy string */
1048 lua_pushvalue(L
, -2); /* get string library */
1049 lua_setfield(L
, -2, "__index"); /* metatable.__index = string */
1050 lua_pop(L
, 1); /* pop metatable */
1055 ** Open string library
1057 LUAMOD_API
int luaopen_string(lua_State
*L
) {
1058 luaL_newlib(L
, strlib
);