| 744 | |
| 745 | |
| 746 | static int str_gsub (lua_State *L) { |
| 747 | size_t srcl, lp; |
| 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 == '^'); |
| 753 | size_t n = 0; |
| 754 | MatchState ms; |
| 755 | luaL_Buffer b; |
| 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); |
| 760 | if (anchor) { |
| 761 | p++; lp--; /* skip anchor character */ |
| 762 | } |
| 763 | ms.L = L; |
| 764 | ms.matchdepth = MAXCCALLS; |
| 765 | ms.src_init = src; |
| 766 | ms.src_end = src+srcl; |
| 767 | ms.p_end = p + lp; |
| 768 | while (n < max_s) { |
| 769 | const char *e; |
| 770 | ms.level = 0; |
| 771 | lua_assert(ms.matchdepth == MAXCCALLS); |
| 772 | e = match(&ms, src, p); |
| 773 | if (e) { |
| 774 | n++; |
| 775 | add_value(&ms, &b, src, e, tr); |
| 776 | } |
| 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++); |
| 781 | else break; |
| 782 | if (anchor) break; |
| 783 | } |
| 784 | luaL_addlstring(&b, src, ms.src_end-src); |
| 785 | luaL_pushresult(&b); |
| 786 | lua_pushinteger(L, n); /* number of substitutions */ |
| 787 | return 2; |
| 788 | } |
| 789 | |
| 790 | /* }====================================================== */ |
| 791 |
nothing calls this directly
no test coverage detected