I see a list of Lua string functions and I see the .gsub()
, for global search and replace: http://www.gammon.com.au/scripts/doc.php?general=lua_string
All lua string functions :
static const luaL_Reg strlib[] = {
{"byte", str_byte},
{"char", str_char},
{"dump", str_dump},
{"find", str_find},
{"format", str_format},
{"gfind", gfind_nodef},
{"gmatch", gmatch},
{"gsub", str_gsub},
{"len", str_len},
{"lower", str_lower},
{"match", str_match},
{"rep", str_rep},
{"reverse", str_reverse},
{"sub", str_sub},
{"upper", str_upper},
{NULL, NULL}
};
Why is there no simple, fast, litteral (non-regex) string replace function?
Is .gsub()
so efficient that there is no benefit?
I found this written in 2006 but it does not seem like it's included: http://lua-users.org/wiki/StringReplace
This is likely because
gsub
is capable of doing exactly what areplace
function would do, and Lua's design goals include that of a small, generally uncomplicated standard library. There's no need for a redundancy like this to be baked right into the language.As an outside example, the Ruby programming language provides both
String#gsub
andString#replace
in its standard library. Ruby is a much, much larger language out of the box because of decisions like this.However, Lua prides itself on being a very easy language to extend. The link you've shown shows how to bake the function into the standard library when compiling Lua as a whole. You could also piece it together to create a module.
Quickly patching together the parts we need results in (note we need the
lmemfind
function from lstrlib.c):We can compile this into a shared object with the proper linkage (
cc -shared
,cc -bundle
, etc...), and load it into Lua like any other module withrequire
.This answer is a formalized reconstruction of the comments above.