From be06e2448b3ac6bfe024efd5cf99dd19fda834b7 Mon Sep 17 00:00:00 2001 From: Arkshine Date: Thu, 4 Feb 2016 15:39:59 +0100 Subject: [PATCH] Add fmt() native to format and return inline a string --- amxmodx/string.cpp | 15 +++++++++++++++ plugins/include/string.inc | 24 +++++++++++++++++++++++- 2 files changed, 38 insertions(+), 1 deletion(-) diff --git a/amxmodx/string.cpp b/amxmodx/string.cpp index fc6ce51b..3b3f4ba4 100755 --- a/amxmodx/string.cpp +++ b/amxmodx/string.cpp @@ -1409,6 +1409,20 @@ static cell AMX_NATIVE_CALL vformat(AMX *amx, cell *params) } +#define MAX_FMT_LENGTH 256 + +// native [MAX_FMT_LENGTH] fmt(const fmt[], any:...) +static cell AMX_NATIVE_CALL fmt(AMX *amx, cell *params) +{ + int length; + const char *string = format_amxstring(amx, params, 1, length); + + size_t num_params = *params / sizeof(cell); + + set_amxstring_utf8_char(amx, params[num_params + 1], string, length, MAX_FMT_LENGTH - 1); + + return 1; +}; AMX_NATIVE_INFO string_Natives[] = @@ -1420,6 +1434,7 @@ AMX_NATIVE_INFO string_Natives[] = {"copyc", copyc}, {"equal", equal}, {"equali", equali}, + {"fmt", fmt}, {"format", format}, {"formatex", formatex}, {"format_args", format_args}, diff --git a/plugins/include/string.inc b/plugins/include/string.inc index 518b1806..c3402ca1 100755 --- a/plugins/include/string.inc +++ b/plugins/include/string.inc @@ -24,7 +24,12 @@ * in the length. This means that this is valid: * copy(string, charsmax(string), ...) */ - + +/** + * Buffer size used by fmt(). + */ +#define MAX_FMT_LENGTH 256 + /** * Calculates the length of a string. * @@ -167,6 +172,23 @@ native format(output[], len, const format[], any:...); */ native formatex(output[], len, const format[], any:...); +/** + * Formats and returns a string according to the AMX Mod X format rules + * (see documentation). + * + * @note Example: menu_additem(menu, fmt("My first %s", "item")). + * @note This should only be used for simple inline formatting like in the above example. + * Avoid using this function to store strings into variables as an additional + * copying step is required. + * @note The buffer size is defined by MAX_FMT_LENGTH. + * + * @param format Formatting rules. + * @param ... Variable number of format parameters. + * + * @return Formatted string + */ +native [MAX_FMT_LENGTH]fmt(const format[], any:...); + /** * Formats a string according to the AMX Mod X format rules (see documentation). *