From 137e6fc7678d67ae7e64c0d4b00140063191bf3f Mon Sep 17 00:00:00 2001 From: MihailRis Date: Sat, 26 Oct 2024 11:24:58 +0300 Subject: [PATCH] add utf8.sub --- doc/en/scripting/builtins/libutf8.md | 3 +++ doc/ru/scripting/builtins/libutf8.md | 3 +++ src/logic/scripting/lua/libs/libutf8.cpp | 11 +++++++++++ 3 files changed, 17 insertions(+) diff --git a/doc/en/scripting/builtins/libutf8.md b/doc/en/scripting/builtins/libutf8.md index 55851f88..e7801f97 100644 --- a/doc/en/scripting/builtins/libutf8.md +++ b/doc/en/scripting/builtins/libutf8.md @@ -15,4 +15,7 @@ utf8.length(text: str) -> int -- Returns the code of the first character of the string utf8.codepoint(chars: str) -> int + +-- Returns a substring from position startchar to endchar inclusive +utf8.sub(text: str, startchar: int, [optional] endchar: int) -> str ``` diff --git a/doc/ru/scripting/builtins/libutf8.md b/doc/ru/scripting/builtins/libutf8.md index 41805b38..b29bb403 100644 --- a/doc/ru/scripting/builtins/libutf8.md +++ b/doc/ru/scripting/builtins/libutf8.md @@ -15,4 +15,7 @@ utf8.length(text: str) -> int -- Возвращает код первого символа строки utf8.codepoint(chars: str) -> int + +-- Возвращает подстроку от позиции startchar до endchar включительно +utf8.sub(text: str, startchar: int, [опционально] endchar: int) -> str ``` diff --git a/src/logic/scripting/lua/libs/libutf8.cpp b/src/logic/scripting/lua/libs/libutf8.cpp index f273284c..182f6295 100644 --- a/src/logic/scripting/lua/libs/libutf8.cpp +++ b/src/logic/scripting/lua/libs/libutf8.cpp @@ -53,10 +53,21 @@ static int l_codepoint(lua::State* L) { return lua::pushinteger(L, util::decode_utf8(size, string.data())); } +static int l_sub(lua::State* L) { + auto string = util::str2u32str_utf8(lua::require_string(L, 1)); + int start = std::max(0, static_cast(lua::tointeger(L, 2) - 1)); + int end = string.length(); + if (lua::gettop(L) >= 3) { + end = std::max(0, static_cast(lua::tointeger(L, 3) - 1)); + } + return lua::pushstring(L, util::u32str2str_utf8(string.substr(start, end))); +} + const luaL_Reg utf8lib[] = { {"tobytes", lua::wrap}, {"tostring", lua::wrap}, {"length", lua::wrap}, {"codepoint", lua::wrap}, + {"sub", lua::wrap}, {NULL, NULL} };