From 38fa9f976c2d920c2fb1e11d5be5d702f7198217 Mon Sep 17 00:00:00 2001 From: xwii Date: Sat, 14 Jan 2023 01:33:13 +0700 Subject: [PATCH] Use `table.move` to implement `common.splice` (#1324) * Use `table.move` to implement `common.splice` * Disallow negative `remove` in `common.splice` --- data/core/common.lua | 19 ++++--------------- 1 file changed, 4 insertions(+), 15 deletions(-) diff --git a/data/core/common.lua b/data/core/common.lua index a4ea01f5..b6c9db67 100644 --- a/data/core/common.lua +++ b/data/core/common.lua @@ -82,25 +82,14 @@ end function common.splice(t, at, remove, insert) + assert(remove >= 0, "bad argument #3 to 'splice' (non-negative value expected)") insert = insert or {} - local offset = #insert - remove - local old_len = #t - if offset < 0 then - for i = at - offset, old_len - offset do - t[i + offset] = t[i] - end - elseif offset > 0 then - for i = old_len, at, -1 do - t[i + offset] = t[i] - end - end - for i, item in ipairs(insert) do - t[at + i - 1] = item - end + local len = #insert + if remove ~= len then table.move(t, at + remove, #t + remove, at + len) end + table.move(insert, 1, len, at, t) end - local function compare_score(a, b) return a.score > b.score end