]>
git.zerfleddert.de Git - proxmark3-svn/blob - liblua/lstrlib.c
fcc61c9a6248f8a8dc9f71d15b13219110ae653b
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
);
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
);
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)); p
+= l
;
122 if (lsep
> 0) { /* avoid empty 'memcpy' (may be expensive) */
123 memcpy(p
, sep
, lsep
* sizeof(char)); p
+= lsep
;
126 memcpy(p
, s
, l
* sizeof(char)); /* last copy (not followed by separator) */
127 luaL_pushresultsize(&b
, totallen
);
133 static int str_byte (lua_State
*L
) {
135 const char *s
= luaL_checklstring(L
, 1, &l
);
136 size_t posi
= posrelat(luaL_optinteger(L
, 2, 1), l
);
137 size_t pose
= posrelat(luaL_optinteger(L
, 3, posi
), l
);
139 if (posi
< 1) posi
= 1;
140 if (pose
> l
) pose
= l
;
141 if (posi
> pose
) return 0; /* empty interval; return no values */
142 n
= (int)(pose
- posi
+ 1);
143 if (posi
+ n
<= pose
) /* (size_t -> int) overflow? */
144 return luaL_error(L
, "string slice too long");
145 luaL_checkstack(L
, n
, "string slice too long");
147 lua_pushinteger(L
, uchar(s
[posi
+i
-1]));
152 static int str_char (lua_State
*L
) {
153 int n
= lua_gettop(L
); /* number of arguments */
156 char *p
= luaL_buffinitsize(L
, &b
, n
);
157 for (i
=1; i
<=n
; i
++) {
158 int c
= luaL_checkint(L
, i
);
159 luaL_argcheck(L
, uchar(c
) == c
, i
, "value out of range");
162 luaL_pushresultsize(&b
, n
);
167 static int writer (lua_State
*L
, const void* b
, size_t size
, void* B
) {
169 luaL_addlstring((luaL_Buffer
*) B
, (const char *)b
, size
);
174 static int str_dump (lua_State
*L
) {
176 luaL_checktype(L
, 1, LUA_TFUNCTION
);
179 if (lua_dump(L
, writer
, &b
) != 0)
180 return luaL_error(L
, "unable to dump given function");
188 ** {======================================================
190 ** =======================================================
194 #define CAP_UNFINISHED (-1)
195 #define CAP_POSITION (-2)
198 typedef struct MatchState
{
199 int matchdepth
; /* control for recursive depth (to avoid C stack overflow) */
200 const char *src_init
; /* init of source string */
201 const char *src_end
; /* end ('\0') of source string */
202 const char *p_end
; /* end ('\0') of pattern */
204 int level
; /* total number of captures (finished or unfinished) */
208 } capture
[LUA_MAXCAPTURES
];
212 /* recursive function */
213 static const char *match (MatchState
*ms
, const char *s
, const char *p
);
216 /* maximum recursion depth for 'match' */
217 #if !defined(MAXCCALLS)
218 #define MAXCCALLS 200
223 #define SPECIALS "^$*+?.([%-"
226 static int check_capture (MatchState
*ms
, int l
) {
228 if (l
< 0 || l
>= ms
->level
|| ms
->capture
[l
].len
== CAP_UNFINISHED
)
229 return luaL_error(ms
->L
, "invalid capture index %%%d", l
+ 1);
234 static int capture_to_close (MatchState
*ms
) {
235 int level
= ms
->level
;
236 for (level
--; level
>=0; level
--)
237 if (ms
->capture
[level
].len
== CAP_UNFINISHED
) return level
;
238 return luaL_error(ms
->L
, "invalid pattern capture");
242 static const char *classend (MatchState
*ms
, const char *p
) {
246 luaL_error(ms
->L
, "malformed pattern (ends with " LUA_QL("%%") ")");
251 do { /* look for a `]' */
253 luaL_error(ms
->L
, "malformed pattern (missing " LUA_QL("]") ")");
254 if (*(p
++) == L_ESC
&& p
< ms
->p_end
)
255 p
++; /* skip escapes (e.g. `%]') */
266 static int match_class (int c
, int cl
) {
268 switch (tolower(cl
)) {
269 case 'a' : res
= isalpha(c
); break;
270 case 'c' : res
= iscntrl(c
); break;
271 case 'd' : res
= isdigit(c
); break;
272 case 'g' : res
= isgraph(c
); break;
273 case 'l' : res
= islower(c
); break;
274 case 'p' : res
= ispunct(c
); break;
275 case 's' : res
= isspace(c
); break;
276 case 'u' : res
= isupper(c
); break;
277 case 'w' : res
= isalnum(c
); break;
278 case 'x' : res
= isxdigit(c
); break;
279 case 'z' : res
= (c
== 0); break; /* deprecated option */
280 default: return (cl
== c
);
282 return (islower(cl
) ? res
: !res
);
286 static int matchbracketclass (int c
, const char *p
, const char *ec
) {
290 p
++; /* skip the `^' */
295 if (match_class(c
, uchar(*p
)))
298 else if ((*(p
+1) == '-') && (p
+2 < ec
)) {
300 if (uchar(*(p
-2)) <= c
&& c
<= uchar(*p
))
303 else if (uchar(*p
) == c
) return sig
;
309 static int singlematch (MatchState
*ms
, const char *s
, const char *p
,
311 if (s
>= ms
->src_end
)
316 case '.': return 1; /* matches any char */
317 case L_ESC
: return match_class(c
, uchar(*(p
+1)));
318 case '[': return matchbracketclass(c
, p
, ep
-1);
319 default: return (uchar(*p
) == c
);
325 static const char *matchbalance (MatchState
*ms
, const char *s
,
327 if (p
>= ms
->p_end
- 1)
328 luaL_error(ms
->L
, "malformed pattern "
329 "(missing arguments to " LUA_QL("%%b") ")");
330 if (*s
!= *p
) return NULL
;
335 while (++s
< ms
->src_end
) {
337 if (--cont
== 0) return s
+1;
339 else if (*s
== b
) cont
++;
342 return NULL
; /* string ends out of balance */
346 static const char *max_expand (MatchState
*ms
, const char *s
,
347 const char *p
, const char *ep
) {
348 ptrdiff_t i
= 0; /* counts maximum expand for item */
349 while (singlematch(ms
, s
+ i
, p
, ep
))
351 /* keeps trying to match with the maximum repetitions */
353 const char *res
= match(ms
, (s
+i
), ep
+1);
355 i
--; /* else didn't match; reduce 1 repetition to try again */
361 static const char *min_expand (MatchState
*ms
, const char *s
,
362 const char *p
, const char *ep
) {
364 const char *res
= match(ms
, s
, ep
+1);
367 else if (singlematch(ms
, s
, p
, ep
))
368 s
++; /* try with one more repetition */
374 static const char *start_capture (MatchState
*ms
, const char *s
,
375 const char *p
, int what
) {
377 int level
= ms
->level
;
378 if (level
>= LUA_MAXCAPTURES
) luaL_error(ms
->L
, "too many captures");
379 ms
->capture
[level
].init
= s
;
380 ms
->capture
[level
].len
= what
;
382 if ((res
=match(ms
, s
, p
)) == NULL
) /* match failed? */
383 ms
->level
--; /* undo capture */
388 static const char *end_capture (MatchState
*ms
, const char *s
,
390 int l
= capture_to_close(ms
);
392 ms
->capture
[l
].len
= s
- ms
->capture
[l
].init
; /* close capture */
393 if ((res
= match(ms
, s
, p
)) == NULL
) /* match failed? */
394 ms
->capture
[l
].len
= CAP_UNFINISHED
; /* undo capture */
399 static const char *match_capture (MatchState
*ms
, const char *s
, int l
) {
401 l
= check_capture(ms
, l
);
402 len
= ms
->capture
[l
].len
;
403 if ((size_t)(ms
->src_end
-s
) >= len
&&
404 memcmp(ms
->capture
[l
].init
, s
, len
) == 0)
410 static const char *match (MatchState
*ms
, const char *s
, const char *p
) {
411 if (ms
->matchdepth
-- == 0)
412 luaL_error(ms
->L
, "pattern too complex");
413 init
: /* using goto's to optimize tail recursion */
414 if (p
!= ms
->p_end
) { /* end of pattern? */
416 case '(': { /* start capture */
417 if (*(p
+ 1) == ')') /* position capture? */
418 s
= start_capture(ms
, s
, p
+ 2, CAP_POSITION
);
420 s
= start_capture(ms
, s
, p
+ 1, CAP_UNFINISHED
);
423 case ')': { /* end capture */
424 s
= end_capture(ms
, s
, p
+ 1);
428 if ((p
+ 1) != ms
->p_end
) /* is the `$' the last char in pattern? */
429 goto dflt
; /* no; go to default */
430 s
= (s
== ms
->src_end
) ? s
: NULL
; /* check end of string */
433 case L_ESC
: { /* escaped sequences not in the format class[*+?-]? */
435 case 'b': { /* balanced string? */
436 s
= matchbalance(ms
, s
, p
+ 2);
438 p
+= 4; goto init
; /* return match(ms, s, p + 4); */
439 } /* else fail (s == NULL) */
442 case 'f': { /* frontier? */
443 const char *ep
; char previous
;
446 luaL_error(ms
->L
, "missing " LUA_QL("[") " after "
447 LUA_QL("%%f") " in pattern");
448 ep
= classend(ms
, p
); /* points to what is next */
449 previous
= (s
== ms
->src_init
) ? '\0' : *(s
- 1);
450 if (!matchbracketclass(uchar(previous
), p
, ep
- 1) &&
451 matchbracketclass(uchar(*s
), p
, ep
- 1)) {
452 p
= ep
; goto init
; /* return match(ms, s, ep); */
454 s
= NULL
; /* match failed */
457 case '0': case '1': case '2': case '3':
458 case '4': case '5': case '6': case '7':
459 case '8': case '9': { /* capture results (%0-%9)? */
460 s
= match_capture(ms
, s
, uchar(*(p
+ 1)));
462 p
+= 2; goto init
; /* return match(ms, s, p + 2) */
470 default: dflt
: { /* pattern class plus optional suffix */
471 const char *ep
= classend(ms
, p
); /* points to optional suffix */
472 /* does not match at least once? */
473 if (!singlematch(ms
, s
, p
, ep
)) {
474 if (*ep
== '*' || *ep
== '?' || *ep
== '-') { /* accept empty? */
475 p
= ep
+ 1; goto init
; /* return match(ms, s, ep + 1); */
477 else /* '+' or no suffix */
480 else { /* matched once */
481 switch (*ep
) { /* handle optional suffix */
482 case '?': { /* optional */
484 if ((res
= match(ms
, s
+ 1, ep
+ 1)) != NULL
)
487 p
= ep
+ 1; goto init
; /* else return match(ms, s, ep + 1); */
491 case '+': /* 1 or more repetitions */
492 s
++; /* 1 match already done */
494 case '*': /* 0 or more repetitions */
495 s
= max_expand(ms
, s
, p
, ep
);
497 case '-': /* 0 or more repetitions (minimum) */
498 s
= min_expand(ms
, s
, p
, ep
);
500 default: /* no suffix */
501 s
++; p
= ep
; goto init
; /* return match(ms, s + 1, ep); */
514 static const char *lmemfind (const char *s1
, size_t l1
,
515 const char *s2
, size_t l2
) {
516 if (l2
== 0) return s1
; /* empty strings are everywhere */
517 else if (l2
> l1
) return NULL
; /* avoids a negative `l1' */
519 const char *init
; /* to search for a `*s2' inside `s1' */
520 l2
--; /* 1st char will be checked by `memchr' */
521 l1
= l1
-l2
; /* `s2' cannot be found after that */
522 while (l1
> 0 && (init
= (const char *)memchr(s1
, *s2
, l1
)) != NULL
) {
523 init
++; /* 1st char is already checked */
524 if (memcmp(init
, s2
+1, l2
) == 0)
526 else { /* correct `l1' and `s1' to try again */
531 return NULL
; /* not found */
536 static void push_onecapture (MatchState
*ms
, int i
, const char *s
,
538 if (i
>= ms
->level
) {
539 if (i
== 0) /* ms->level == 0, too */
540 lua_pushlstring(ms
->L
, s
, e
- s
); /* add whole match */
542 luaL_error(ms
->L
, "invalid capture index");
545 ptrdiff_t l
= ms
->capture
[i
].len
;
546 if (l
== CAP_UNFINISHED
) luaL_error(ms
->L
, "unfinished capture");
547 if (l
== CAP_POSITION
)
548 lua_pushinteger(ms
->L
, ms
->capture
[i
].init
- ms
->src_init
+ 1);
550 lua_pushlstring(ms
->L
, ms
->capture
[i
].init
, l
);
555 static int push_captures (MatchState
*ms
, const char *s
, const char *e
) {
557 int nlevels
= (ms
->level
== 0 && s
) ? 1 : ms
->level
;
558 luaL_checkstack(ms
->L
, nlevels
, "too many captures");
559 for (i
= 0; i
< nlevels
; i
++)
560 push_onecapture(ms
, i
, s
, e
);
561 return nlevels
; /* number of strings pushed */
565 /* check whether pattern has no special characters */
566 static int nospecials (const char *p
, size_t l
) {
569 if (strpbrk(p
+ upto
, SPECIALS
))
570 return 0; /* pattern has a special character */
571 upto
+= strlen(p
+ upto
) + 1; /* may have more after \0 */
573 return 1; /* no special chars found */
577 static int str_find_aux (lua_State
*L
, int find
) {
579 const char *s
= luaL_checklstring(L
, 1, &ls
);
580 const char *p
= luaL_checklstring(L
, 2, &lp
);
581 size_t init
= posrelat(luaL_optinteger(L
, 3, 1), ls
);
582 if (init
< 1) init
= 1;
583 else if (init
> ls
+ 1) { /* start after string's end? */
584 lua_pushnil(L
); /* cannot find anything */
587 /* explicit request or no special characters? */
588 if (find
&& (lua_toboolean(L
, 4) || nospecials(p
, lp
))) {
589 /* do a plain search */
590 const char *s2
= lmemfind(s
+ init
- 1, ls
- init
+ 1, p
, lp
);
592 lua_pushinteger(L
, s2
- s
+ 1);
593 lua_pushinteger(L
, s2
- s
+ lp
);
599 const char *s1
= s
+ init
- 1;
600 int anchor
= (*p
== '^');
602 p
++; lp
--; /* skip anchor character */
605 ms
.matchdepth
= MAXCCALLS
;
612 lua_assert(ms
.matchdepth
== MAXCCALLS
);
613 if ((res
=match(&ms
, s1
, p
)) != NULL
) {
615 lua_pushinteger(L
, s1
- s
+ 1); /* start */
616 lua_pushinteger(L
, res
- s
); /* end */
617 return push_captures(&ms
, NULL
, 0) + 2;
620 return push_captures(&ms
, s1
, res
);
622 } while (s1
++ < ms
.src_end
&& !anchor
);
624 lua_pushnil(L
); /* not found */
629 static int str_find (lua_State
*L
) {
630 return str_find_aux(L
, 1);
634 static int str_match (lua_State
*L
) {
635 return str_find_aux(L
, 0);
639 static int gmatch_aux (lua_State
*L
) {
642 const char *s
= lua_tolstring(L
, lua_upvalueindex(1), &ls
);
643 const char *p
= lua_tolstring(L
, lua_upvalueindex(2), &lp
);
646 ms
.matchdepth
= MAXCCALLS
;
650 for (src
= s
+ (size_t)lua_tointeger(L
, lua_upvalueindex(3));
655 lua_assert(ms
.matchdepth
== MAXCCALLS
);
656 if ((e
= match(&ms
, src
, p
)) != NULL
) {
657 lua_Integer newstart
= e
-s
;
658 if (e
== src
) newstart
++; /* empty match? go at least one position */
659 lua_pushinteger(L
, newstart
);
660 lua_replace(L
, lua_upvalueindex(3));
661 return push_captures(&ms
, src
, e
);
664 return 0; /* not found */
668 static int gmatch (lua_State
*L
) {
669 luaL_checkstring(L
, 1);
670 luaL_checkstring(L
, 2);
672 lua_pushinteger(L
, 0);
673 lua_pushcclosure(L
, gmatch_aux
, 3);
678 static void add_s (MatchState
*ms
, luaL_Buffer
*b
, const char *s
,
681 const char *news
= lua_tolstring(ms
->L
, 3, &l
);
682 for (i
= 0; i
< l
; i
++) {
683 if (news
[i
] != L_ESC
)
684 luaL_addchar(b
, news
[i
]);
687 if (!isdigit(uchar(news
[i
]))) {
688 if (news
[i
] != L_ESC
)
689 luaL_error(ms
->L
, "invalid use of " LUA_QL("%c")
690 " in replacement string", L_ESC
);
691 luaL_addchar(b
, news
[i
]);
693 else if (news
[i
] == '0')
694 luaL_addlstring(b
, s
, e
- s
);
696 push_onecapture(ms
, news
[i
] - '1', s
, e
);
697 luaL_addvalue(b
); /* add capture to accumulated result */
704 static void add_value (MatchState
*ms
, luaL_Buffer
*b
, const char *s
,
705 const char *e
, int tr
) {
706 lua_State
*L
= ms
->L
;
708 case LUA_TFUNCTION
: {
711 n
= push_captures(ms
, s
, e
);
716 push_onecapture(ms
, 0, s
, e
);
720 default: { /* LUA_TNUMBER or LUA_TSTRING */
725 if (!lua_toboolean(L
, -1)) { /* nil or false? */
727 lua_pushlstring(L
, s
, e
- s
); /* keep original text */
729 else if (!lua_isstring(L
, -1))
730 luaL_error(L
, "invalid replacement value (a %s)", luaL_typename(L
, -1));
731 luaL_addvalue(b
); /* add result to accumulator */
735 static int str_gsub (lua_State
*L
) {
737 const char *src
= luaL_checklstring(L
, 1, &srcl
);
738 const char *p
= luaL_checklstring(L
, 2, &lp
);
739 int tr
= lua_type(L
, 3);
740 size_t max_s
= luaL_optinteger(L
, 4, srcl
+1);
741 int anchor
= (*p
== '^');
745 luaL_argcheck(L
, tr
== LUA_TNUMBER
|| tr
== LUA_TSTRING
||
746 tr
== LUA_TFUNCTION
|| tr
== LUA_TTABLE
, 3,
747 "string/function/table expected");
748 luaL_buffinit(L
, &b
);
750 p
++; lp
--; /* skip anchor character */
753 ms
.matchdepth
= MAXCCALLS
;
755 ms
.src_end
= src
+srcl
;
760 lua_assert(ms
.matchdepth
== MAXCCALLS
);
761 e
= match(&ms
, src
, p
);
764 add_value(&ms
, &b
, src
, e
, tr
);
766 if (e
&& e
>src
) /* non empty match? */
767 src
= e
; /* skip it */
768 else if (src
< ms
.src_end
)
769 luaL_addchar(&b
, *src
++);
773 luaL_addlstring(&b
, src
, ms
.src_end
-src
);
775 lua_pushinteger(L
, n
); /* number of substitutions */
779 /* }====================================================== */
784 ** {======================================================
786 ** =======================================================
790 ** LUA_INTFRMLEN is the length modifier for integer conversions in
791 ** 'string.format'; LUA_INTFRM_T is the integer type corresponding to
792 ** the previous length
794 #if !defined(LUA_INTFRMLEN) /* { */
795 #if defined(LUA_USE_LONGLONG)
797 #define LUA_INTFRMLEN "ll"
798 #define LUA_INTFRM_T long long
802 #define LUA_INTFRMLEN "l"
803 #define LUA_INTFRM_T long
810 ** LUA_FLTFRMLEN is the length modifier for float conversions in
811 ** 'string.format'; LUA_FLTFRM_T is the float type corresponding to
812 ** the previous length
814 #if !defined(LUA_FLTFRMLEN)
816 #define LUA_FLTFRMLEN ""
817 #define LUA_FLTFRM_T double
822 /* maximum size of each formatted item (> len(format('%99.99f', -1e308))) */
824 /* valid flags in a format specification */
825 #define FLAGS "-+ #0"
827 ** maximum size of each format specification (such as '%-099.99d')
828 ** (+10 accounts for %99.99x plus margin of error)
830 #define MAX_FORMAT (sizeof(FLAGS) + sizeof(LUA_INTFRMLEN) + 10)
833 static void addquoted (lua_State
*L
, luaL_Buffer
*b
, int arg
) {
835 const char *s
= luaL_checklstring(L
, arg
, &l
);
836 luaL_addchar(b
, '"');
838 if (*s
== '"' || *s
== '\\' || *s
== '\n') {
839 luaL_addchar(b
, '\\');
842 else if (*s
== '\0' || iscntrl(uchar(*s
))) {
844 if (!isdigit(uchar(*(s
+1))))
845 sprintf(buff
, "\\%d", (int)uchar(*s
));
847 sprintf(buff
, "\\%03d", (int)uchar(*s
));
848 luaL_addstring(b
, buff
);
854 luaL_addchar(b
, '"');
857 static const char *scanformat (lua_State
*L
, const char *strfrmt
, char *form
) {
858 const char *p
= strfrmt
;
859 while (*p
!= '\0' && strchr(FLAGS
, *p
) != NULL
) p
++; /* skip flags */
860 if ((size_t)(p
- strfrmt
) >= sizeof(FLAGS
)/sizeof(char))
861 luaL_error(L
, "invalid format (repeated flags)");
862 if (isdigit(uchar(*p
))) p
++; /* skip width */
863 if (isdigit(uchar(*p
))) p
++; /* (2 digits at most) */
866 if (isdigit(uchar(*p
))) p
++; /* skip precision */
867 if (isdigit(uchar(*p
))) p
++; /* (2 digits at most) */
869 if (isdigit(uchar(*p
)))
870 luaL_error(L
, "invalid format (width or precision too long)");
872 memcpy(form
, strfrmt
, (p
- strfrmt
+ 1) * sizeof(char));
873 form
+= p
- strfrmt
+ 1;
880 ** add length modifier into formats
882 static void addlenmod (char *form
, const char *lenmod
) {
883 size_t l
= strlen(form
);
884 size_t lm
= strlen(lenmod
);
885 char spec
= form
[l
- 1];
886 strcpy(form
+ l
- 1, lenmod
);
887 form
[l
+ lm
- 1] = spec
;
892 static int str_format (lua_State
*L
) {
893 int top
= lua_gettop(L
);
896 const char *strfrmt
= luaL_checklstring(L
, arg
, &sfl
);
897 const char *strfrmt_end
= strfrmt
+sfl
;
899 luaL_buffinit(L
, &b
);
900 while (strfrmt
< strfrmt_end
) {
901 if (*strfrmt
!= L_ESC
)
902 luaL_addchar(&b
, *strfrmt
++);
903 else if (*++strfrmt
== L_ESC
)
904 luaL_addchar(&b
, *strfrmt
++); /* %% */
905 else { /* format item */
906 char form
[MAX_FORMAT
]; /* to store the format (`%...') */
907 char *buff
= luaL_prepbuffsize(&b
, MAX_ITEM
); /* to put formatted item */
908 int nb
= 0; /* number of bytes in added item */
910 luaL_argerror(L
, arg
, "no value");
911 strfrmt
= scanformat(L
, strfrmt
, form
);
912 switch (*strfrmt
++) {
914 nb
= sprintf(buff
, form
, luaL_checkint(L
, arg
));
917 case 'd': case 'i': {
918 lua_Number n
= luaL_checknumber(L
, arg
);
919 LUA_INTFRM_T ni
= (LUA_INTFRM_T
)n
;
920 lua_Number diff
= n
- (lua_Number
)ni
;
921 luaL_argcheck(L
, -1 < diff
&& diff
< 1, arg
,
922 "not a number in proper range");
923 addlenmod(form
, LUA_INTFRMLEN
);
924 nb
= sprintf(buff
, form
, ni
);
927 case 'o': case 'u': case 'x': case 'X': {
928 lua_Number n
= luaL_checknumber(L
, arg
);
929 unsigned LUA_INTFRM_T ni
= (unsigned LUA_INTFRM_T
)n
;
930 lua_Number diff
= n
- (lua_Number
)ni
;
931 luaL_argcheck(L
, -1 < diff
&& diff
< 1, arg
,
932 "not a non-negative number in proper range");
933 addlenmod(form
, LUA_INTFRMLEN
);
934 nb
= sprintf(buff
, form
, ni
);
937 case 'e': case 'E': case 'f':
938 #if defined(LUA_USE_AFORMAT)
941 case 'g': case 'G': {
942 addlenmod(form
, LUA_FLTFRMLEN
);
943 nb
= sprintf(buff
, form
, (LUA_FLTFRM_T
)luaL_checknumber(L
, arg
));
947 addquoted(L
, &b
, arg
);
952 const char *s
= luaL_tolstring(L
, arg
, &l
);
953 if (!strchr(form
, '.') && l
>= 100) {
954 /* no precision and string is too long to be formatted;
955 keep original string */
960 nb
= sprintf(buff
, form
, s
);
961 lua_pop(L
, 1); /* remove result from 'luaL_tolstring' */
965 default: { /* also treat cases `pnLlh' */
966 return luaL_error(L
, "invalid option " LUA_QL("%%%c") " to "
967 LUA_QL("format"), *(strfrmt
- 1));
970 luaL_addsize(&b
, nb
);
977 /* }====================================================== */
980 static const luaL_Reg strlib
[] = {
985 {"format", str_format
},
989 {"lower", str_lower
},
990 {"match", str_match
},
992 {"reverse", str_reverse
},
994 {"upper", str_upper
},
999 static void createmetatable (lua_State
*L
) {
1000 lua_createtable(L
, 0, 1); /* table to be metatable for strings */
1001 lua_pushliteral(L
, ""); /* dummy string */
1002 lua_pushvalue(L
, -2); /* copy table */
1003 lua_setmetatable(L
, -2); /* set table as metatable for strings */
1004 lua_pop(L
, 1); /* pop dummy string */
1005 lua_pushvalue(L
, -2); /* get string library */
1006 lua_setfield(L
, -2, "__index"); /* metatable.__index = string */
1007 lua_pop(L
, 1); /* pop metatable */
1012 ** Open string library
1014 LUAMOD_API
int luaopen_string (lua_State
*L
) {
1015 luaL_newlib(L
, strlib
);