From 68ad7b4fcf12bd3d1b19f4eea40882ce981ccce4 Mon Sep 17 00:00:00 2001 From: Infi-power <75531788+Infi-power@users.noreply.github.com> Date: Fri, 24 Nov 2023 08:40:29 +0000 Subject: [PATCH] Rework touchscreen `insert` command and add `delete` command (#40) Co-authored-by: OgelGames --- docs/touchscreen.md | 15 ++++++++++++--- touchscreen.lua | 25 +++++++++++++++++++------ 2 files changed, 31 insertions(+), 9 deletions(-) diff --git a/docs/touchscreen.md b/docs/touchscreen.md index 4bd5697..1bb05bc 100644 --- a/docs/touchscreen.md +++ b/docs/touchscreen.md @@ -34,7 +34,7 @@ digiline_send("touchscreen", { }) ``` -**`insert`** - Adds an element at a specific index. +**`insert`** - Adds an element at a specific index. The index can be any positive number. ```lua digiline_send("touchscreen", { @@ -63,7 +63,7 @@ digiline_send("touchscreen", { }) ``` -**`remove`** - Removes an element. +**`remove`** - Removes an element, shifting elements to fill the space. ```lua digiline_send("touchscreen", { @@ -72,7 +72,16 @@ digiline_send("touchscreen", { }) ``` -**`clear`** - Removes all elements, but keeps settings. +**`delete`** - Removes an element without changing element indexes. + +```lua +digiline_send("touchscreen", { + command = "delete", + index = 1, +}) +``` + +**`clear`** - Removes all elements. ```lua digiline_send("touchscreen", { diff --git a/touchscreen.lua b/touchscreen.lua index 15311d4..2335339 100644 --- a/touchscreen.lua +++ b/touchscreen.lua @@ -73,11 +73,7 @@ local function process_command(meta, data, msg) local index = tonumber(msg.index) if element and index and index > 0 then local str = create_element_string(element, msg) - if index > #data then - table.insert(data, str) - else - table.insert(data, index, str) - end + table.insert(data, index, str) end elseif cmd == "replace" then @@ -101,6 +97,12 @@ local function process_command(meta, data, msg) table.remove(data, index) end + elseif cmd == "delete" then + local index = tonumber(msg.index) + if index and data[index] then + data[index] = nil + end + elseif cmd == "set" then if msg.locked ~= nil then meta:set_int("locked", msg.locked == false and 0 or 1) @@ -161,7 +163,18 @@ local function create_formspec(meta, data) if focus then fs = fs.."set_focus["..focus.."]" end - return fs..table.concat(data) + local data_size = 0 + for i in pairs(data) do + if i > data_size then + data_size = i + end + end + for i=1, data_size do + if data[i] then + fs = fs..data[i] + end + end + return fs end local function update_formspec(pos, meta, data)