WFL: Add replace_all, starts_with, and ends_with string functions.

The latter two are also added to the Lua stringx module.
This commit is contained in:
Celtic Minstrel 2024-09-08 00:20:08 -04:00 committed by Celtic Minstrel
parent 1b63da9974
commit fc86cb0b93
2 changed files with 43 additions and 0 deletions

View file

@ -61,6 +61,22 @@ function stringx.iter_ranges(str)
end)
end
---Test if a string begins with a specified prefix
---@param s string The string to test
---@param p string The prefix to check
---@return boolean
function stringx.starts_with(s, p)
return s:sub(0, #p) == p
end
---Test if a string end with a specified suffix
---@param s string The string to test
---@param p string The suffix to check
---@return boolean
function stringx.ends_with(s, p)
return s:sub(-#p) == p
end
wesnoth.format = wesnoth.deprecate_api('wesnoth.format', 'stringx.vformat', 1, nil, stringx.vformat)
wesnoth.format_conjunct_list = wesnoth.deprecate_api('wesnoth.format_conjunct_list', 'stringx.format_conjunct_list', 1, nil, stringx.format_conjunct_list)
wesnoth.format_disjunct_list = wesnoth.deprecate_api('wesnoth.format_disjunct_list', 'stringx.format_disjunct_list', 1, nil, stringx.format_disjunct_list)

View file

@ -23,6 +23,7 @@
#include "log.hpp"
#include "pathutils.hpp"
#include <boost/algorithm/string.hpp>
#include <boost/math/constants/constants.hpp>
#include <cctype>
#include <deque>
@ -448,6 +449,29 @@ DEFINE_WFL_FUNCTION(replace, 3, 4)
return variant(result.replace(offset, std::string::npos, replacement));
}
DEFINE_WFL_FUNCTION(replace_all, 3, 3)
{
std::string result = args()[0]->evaluate(variables, fdb).as_string();
std::string needle = args()[1]->evaluate(variables, fdb).as_string();
std::string replacement = args().back()->evaluate(variables, fdb).as_string();
boost::replace_all(result, needle, replacement);
return variant(result);
}
DEFINE_WFL_FUNCTION(starts_with, 2, 2)
{
std::string str = args()[0]->evaluate(variables, fdb).as_string();
std::string prefix = args()[1]->evaluate(variables, fdb).as_string();
return variant(boost::starts_with(str, prefix));
}
DEFINE_WFL_FUNCTION(ends_with, 2, 2)
{
std::string str = args()[0]->evaluate(variables, fdb).as_string();
std::string prefix = args()[1]->evaluate(variables, fdb).as_string();
return variant(boost::ends_with(str, prefix));
}
DEFINE_WFL_FUNCTION(insert, 3, 3)
{
std::string result = args()[0]->evaluate(variables, fdb).as_string();
@ -1579,6 +1603,9 @@ std::shared_ptr<function_symbol_table> function_symbol_table::get_builtins()
DECLARE_WFL_FUNCTION(tomap);
DECLARE_WFL_FUNCTION(substring);
DECLARE_WFL_FUNCTION(replace);
DECLARE_WFL_FUNCTION(replace_all);
DECLARE_WFL_FUNCTION(starts_with);
DECLARE_WFL_FUNCTION(ends_with);
DECLARE_WFL_FUNCTION(length);
DECLARE_WFL_FUNCTION(concatenate);
DECLARE_WFL_FUNCTION(sin);