New function 'luaL_addgsub'
Added a new function 'luaL_addgsub', similar to 'luaL_gsub' but that adds its result directly to a preexisting buffer, avoiding the creation of one extra intermediate string. Also added two simple macros, 'luaL_bufflen' and 'luaL_buffaddr', to query the current length and the contents address of a buffer.
This commit is contained in:
20
lauxlib.c
20
lauxlib.c
@@ -951,18 +951,24 @@ LUALIB_API void luaL_requiref (lua_State *L, const char *modname,
|
||||
}
|
||||
|
||||
|
||||
LUALIB_API const char *luaL_gsub (lua_State *L, const char *s, const char *p,
|
||||
const char *r) {
|
||||
LUALIB_API void luaL_addgsub (luaL_Buffer *b, const char *s,
|
||||
const char *p, const char *r) {
|
||||
const char *wild;
|
||||
size_t l = strlen(p);
|
||||
luaL_Buffer b;
|
||||
luaL_buffinit(L, &b);
|
||||
while ((wild = strstr(s, p)) != NULL) {
|
||||
luaL_addlstring(&b, s, wild - s); /* push prefix */
|
||||
luaL_addstring(&b, r); /* push replacement in place of pattern */
|
||||
luaL_addlstring(b, s, wild - s); /* push prefix */
|
||||
luaL_addstring(b, r); /* push replacement in place of pattern */
|
||||
s = wild + l; /* continue after 'p' */
|
||||
}
|
||||
luaL_addstring(&b, s); /* push last suffix */
|
||||
luaL_addstring(b, s); /* push last suffix */
|
||||
}
|
||||
|
||||
|
||||
LUALIB_API const char *luaL_gsub (lua_State *L, const char *s,
|
||||
const char *p, const char *r) {
|
||||
luaL_Buffer b;
|
||||
luaL_buffinit(L, &b);
|
||||
luaL_addgsub(&b, s, p, r);
|
||||
luaL_pushresult(&b);
|
||||
return lua_tostring(L, -1);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user