Skip to content

Instantly share code, notes, and snippets.

@gilzoide
Last active September 7, 2021 14:03
Show Gist options
  • Save gilzoide/d3ee8cddf786e6072c8a39168602787d to your computer and use it in GitHub Desktop.
Save gilzoide/d3ee8cddf786e6072c8a39168602787d to your computer and use it in GitHub Desktop.
A plain string replacement function for Lua with no magic characters
#include "lua.h"
#include "lualib.h"
#include "lauxlib.h"
/// Performs plain substring replacement, with no characters in `pattern` or `replacement` being considered magic.
/// There is no support for `string.gsub`'s parameter `n` and second return in this version.
/// @function string.replace
/// @tparam string str
/// @tparam string pattern
/// @tparam string replacement
/// @treturn string
int string_replace(lua_State *L) {
const char *s = luaL_checkstring(L, 1);
const char *p = luaL_checkstring(L, 2);
const char *r = luaL_checkstring(L, 3);
luaL_gsub(L, s, p, r);
return 1;
}
// Call this to register the `replace` function into the `string` library.
// E.g.: while setting up a new `lua_State` or from some `luaopen_*` function.
void register_plaingsub(lua_State *L) {
// string.replace = &string_replace
lua_getglobal(L, "string");
lua_pushcfunction(L, &string_replace);
lua_setfield(L, -2, "replace");
lua_pop(L, 1); // pop string
}
void test_plaingsub(lua_State *L) {
luaL_dostring(L, "assert(string.replace('Dot.percent.arent.magic', '.', '%') == 'Dot%percent%arent%magic')");
}
--- Performs plain substring replacement, with no characters in `pattern` or `replacement` being considered magic.
-- @tparam string str
-- @tparam string pattern
-- @tparam string replacement
-- @param[opt] n
-- @treturn string
-- @treturn number
function string.replace(s, patt, repl, n)
return string.gsub(s, string.gsub(patt, "%p", "%%%0"), string.gsub(repl, "%%", "%%%%"), n)
end
assert(string.replace('Dot.percent.arent.magic', '.', '%') == 'Dot%percent%arent%magic')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment