diff --git a/README.md b/README.md index dfefa10c..3da2e61c 100644 --- a/README.md +++ b/README.md @@ -45,7 +45,7 @@ Full per-function reference: **[docs/API.md](docs/API.md)**. | [Loot](docs/API.md#loot) | `C_Loot.GetNearbyLootableUnits`, `C_Loot.GetLastScanResults`, `C_Loot.IsScanInProgress`, `C_Loot.LootUnit`, `C_Loot.LootUnitItem`, `C_Loot.ScanNearbyLoot` | | [LootHistory](docs/API.md#loothistory) | `C_LootHistory.GetNumItems`, `C_LootHistory.GetItem`, `C_LootHistory.GetPlayerInfo`, `C_LootHistory.Clear` | | [LossOfControl](docs/API.md#lossofcontrol) | `C_LossOfControl.GetActiveLossOfControlData`, `C_LossOfControl.GetActiveLossOfControlDataCount` | -| [Lua](docs/API.md#lua) | `coroutine.create`, `coroutine.resume`, `coroutine.status`, `coroutine.wrap`, `coroutine.yield`, `math.fmod`, `select`, `string.gmatch`, `string.match`, `table.wipe` | +| [Lua](docs/API.md#lua) | `coroutine.create`, `coroutine.resume`, `coroutine.status`, `coroutine.wrap`, `coroutine.yield`, `math.fmod`, `select`, `string.gmatch`, `string.match`, `strsplit`, `table.wipe` | | [Macros](docs/API.md#macros) | `GetLooseMacroIcons`, `GetLooseMacroItemIcons`, `GetMacroIcons`, `GetMacroItemIcons`, `GetMacroSpell` | | [Mail](docs/API.md#mail) | `GetInboxItemLink`, `GetSendMailItemLink` | | [Map](docs/API.md#map) | `C_Map.GetAreaInfo`, `C_Map.GetAreas`, `C_Map.GetAreaTriggerInfo`, `C_Map.GetAreaTriggers`, `C_Map.GetBestMapForUnit`, `C_Map.GetMapAreaIDs`, `C_Map.GetMapOverlays`, `C_Map.GetMapWorldSize` | diff --git a/docs/API.md b/docs/API.md index 034e05e1..729ebfa2 100644 --- a/docs/API.md +++ b/docs/API.md @@ -282,6 +282,7 @@ build instructions. - [`select(index, ...)`](#selectindex-) - [`table.wipe(t)`](#tablewipet) - [`string.match` / `string.gmatch`](#stringmatch--stringgmatch) + - [`strsplit(sep, str [, pieces])`](#strsplitsep-str--pieces) - [`math.fmod(x, y)`](#mathfmodx-y) - [`coroutine.create(fn)`](#coroutinecreatefn) - [`coroutine.resume(co, ...)`](#coroutineresumeco-) @@ -6839,6 +6840,31 @@ for word in string.gmatch("a,bb,ccc", "[^,]+") do print(word) end -- a / bb / cc > a hot VM-core function. This is the long-standing vanilla 1.12 constraint — > always write `string.match(s, p)`, never `s:match(p)`. +### `strsplit(sep, str [, pieces])` + +The WoW global (backported from 3.3.5), splits `str` on **any** character in +`sep` and returns the pieces as multiple values. + +- `sep` — a set of delimiter *characters* (not a pattern); each character is + a delimiter. `","` splits on commas; `" -"` splits on spaces and dashes. +- `pieces` (optional) — caps the number of results. After `pieces - 1` + splits the rest of the string (delimiters and all) is returned as the final + piece. `0` or omitted = unlimited. `1` returns the whole string unsplit. + +Consecutive/trailing delimiters produce empty pieces, matching retail. + +```lua +strsplit(",", "a,b,c") -- "a", "b", "c" +strsplit(",", "a,b,c,d", 2) -- "a", "b,c,d" (capped at 2) +strsplit(" -", "a b-c") -- "a", "b", "c" (space OR dash) +strsplit(",", "a,,b") -- "a", "", "b" (empty middle piece) +local zone, x, y = strsplit(":", "Durotar:52:38") +``` + +Errors `strsplit(): Stack overflow` if a string splits into more pieces than +the Lua stack can grow to hold (`lua_checkstack` guards every push) — the +same guard and message 3.3.5 uses. + ### `math.fmod(x, y)` The floating-point remainder of `x / y` (the quotient truncated toward zero), diff --git a/src/Game.cpp b/src/Game.cpp index 9560ea91..751ca198 100644 --- a/src/Game.cpp +++ b/src/Game.cpp @@ -57,7 +57,8 @@ namespace Lua { F(Resume, lua_resume, LUA_RESUME) \ F(Yield, lua_yield, LUA_YIELD) \ F(ArgError, luaL_argerror, LUAL_ARG_ERROR) \ - F(SetN, luaL_setn, LUAL_SETN) + F(SetN, luaL_setn, LUAL_SETN) \ + F(CheckStack, lua_checkstack, LUA_CHECK_STACK) #define CLASSICAPI_BIND_LUA(Name, Typedef, Offset) \ const Typedef##_t Name = reinterpret_cast(Offsets::Offset); diff --git a/src/Game.h b/src/Game.h index 014292ef..f824a160 100644 --- a/src/Game.h +++ b/src/Game.h @@ -100,6 +100,7 @@ using lua_resume_t = int(__fastcall *)(void *L, int nargs); using lua_yield_t = int(__fastcall *)(void *L, int nresults); using luaL_argerror_t = void(__fastcall *)(void *L, int narg, const char *msg); using luaL_setn_t = void(__fastcall *)(void *L, int t, int n); +using lua_checkstack_t = int(__fastcall *)(void *L, int size); extern const lua_isnumber_t IsNumber; extern const lua_isstring_t IsString; @@ -142,6 +143,7 @@ extern const lua_resume_t Resume; extern const lua_yield_t Yield; extern const luaL_argerror_t ArgError; extern const luaL_setn_t SetN; +extern const lua_checkstack_t CheckStack; // Returns the global `lua_State *` (read on demand from the engine's global). // Callable outside a Lua callback, e.g. during LoadScriptFunctions setup. diff --git a/src/Offsets.h b/src/Offsets.h index 727e5f98..77ab5b5f 100644 --- a/src/Offsets.h +++ b/src/Offsets.h @@ -3796,6 +3796,14 @@ enum Offsets { // `rawset(nil)` clear leaves it stale and subsequent `table.insert` // appends past the wiped slots. LUAL_SETN = 0x6F4EA0, + // `lua_checkstack(L, n)` — `int __fastcall(L /*ecx*/, n /*edx*/)`. + // Ensures room for `n` more stack values, growing if needed; returns 0 + // (without growing) when `(top-base)/16 + n` would exceed LUA_MAXCSTACK + // (0x800 = 2048), 1 otherwise. Verified by the `cmp reg, 0x800` overflow + // test at 0x006F2F43. Needed by any C function that pushes an unbounded + // number of results (e.g. `strsplit`) — pushing past the ~20-slot + // C-call guarantee without growing corrupts the stack. + LUA_CHECK_STACK = 0x006F2F30, // `str_find` — the Lua 5.0 string-library `string.find` C function // (`int __fastcall(void *L)`), entry in the strlib luaL_reg table at // `0x00822dd0`. Returns `1` (nil pushed, no match), `2` (start, end), diff --git a/src/baselib/StringLib.cpp b/src/baselib/StringLib.cpp index eba03e4a..38fa586a 100644 --- a/src/baselib/StringLib.cpp +++ b/src/baselib/StringLib.cpp @@ -11,16 +11,18 @@ // You should have received a copy of the GNU General Public License along with // ClassicAPI. If not, see . -// Lua 5.1 string-library additions that 1.12's Lua 5.0 is missing: +// String helpers that 1.12's Lua 5.0 is missing: // -// - `string.match(s, pattern [, init])` — first-match extraction. -// - `string.gmatch(s, pattern)` — match iterator. +// - `string.match(s, pattern [, init])` — first-match extraction (5.1). +// - `string.gmatch(s, pattern)` — match iterator (5.1). +// - `strsplit(sep, str [, pieces])` — WoW global; split on any char. // -// Both are the same underlying pattern engine as functions 5.0 already ships: +// The two `string.*` ones reuse pattern machinery 5.0 already ships: // - `match` is `find` returning captures / the whole match instead of the // start/end indices — so we call the engine's `str_find` and transform. // - `gmatch` is exactly 5.0's `string.gfind` (renamed in 5.1); we register // it as a direct alias of the engine's `gfind` C function. +// `strsplit` is a hand-rolled port of 3.3.5's `strsplit` (see below). // // NOTE: only the `string.foo(s, ...)` call form works — NOT the // `("x"):foo(...)` method sugar. WoW's Lua VM strips type-metatables for @@ -83,9 +85,68 @@ int __fastcall Script_string_match(void *L) { const auto Script_string_gmatch = reinterpret_cast(Offsets::FUN_LUA_STR_GFIND); +// `strsplit(sep, str [, pieces])` — the WoW global (also aliased as +// `string.split`), split `str` on ANY character in `sep` and return the +// pieces as multiple values. `pieces > 0` caps the result count, with the +// unsplit remainder as the final piece; `0` / omitted = unlimited. Ported +// from 3.3.5's `strsplit` (FUN_00816a60) with one deliberate change: we do +// NOT `lua_settop(L, 0)` up front. Popping the args would leave the source +// string unreferenced, so a GC step triggered by a `pushlstring` could free +// the very buffer we're still scanning. Keeping the args on the stack keeps +// the source GC-rooted; Lua returns the top N values (our pieces) regardless +// of the args sitting below them. Each push is guarded by `lua_checkstack` +// (this pushes an unbounded number of results), erroring like 3.3.5 on +// genuine stack exhaustion. +int __fastcall Script_strsplit(void *L) { + const char *sep = Game::Lua::ToString(L, 1); + const char *str = Game::Lua::ToString(L, 2); + if (sep == nullptr || str == nullptr) { + Game::Lua::Error(L, "Usage: strsplit(\"separators\", str [, pieces])"); + return 0; // unreachable + } + const int pieces = + Game::Lua::IsNumber(L, 3) ? static_cast(Game::Lua::ToNumber(L, 3)) : 0; + + const char *segStart = str; + int count = 0; + // Only scan for separators while unlimited (pieces == 0) or the cap + // hasn't been reached (pieces > 1). pieces == 1 (or <= 0 but non-zero) + // yields the whole string as a single piece — matches 3.3.5. + if (pieces == 0 || pieces > 1) { + for (const char *p = str; *p != '\0'; ++p) { + bool isSep = false; + for (const char *s = sep; *s != '\0'; ++s) { + if (*p == *s) { + isSep = true; + break; + } + } + if (!isSep) + continue; + ++count; + if (Game::Lua::CheckStack(L, count) == 0) { + Game::Lua::Error(L, "strsplit(): Stack overflow"); + return 0; // unreachable + } + Game::Lua::PushLString(L, segStart, + static_cast(p - segStart)); + segStart = p + 1; + if (count == pieces - 1) + break; // cap hit; remainder becomes the final piece + } + } + if (Game::Lua::CheckStack(L, count + 1) == 0) { + Game::Lua::Error(L, "strsplit(): Stack overflow"); + return 0; // unreachable + } + Game::Lua::PushString(L, segStart); // final piece (remainder to end) + return count + 1; +} + void RegisterFns() { Game::Lua::RegisterTableFunction("string", "match", &Script_string_match); Game::Lua::RegisterTableFunction("string", "gmatch", Script_string_gmatch); + Game::Lua::RegisterGlobalFunction("strsplit", &Script_strsplit); } // Both states are Lua 5.0 and equally missing these; RegisterTableFunction