0

I have been trying to make an 'undo' function that you usually have in text editors and programs. I already did make sort of an 'undo' function, but it only removes 1 letter at a time, which is not what i am aiming for. I am going for something that removes whole words at a time.

I used GetPropertyChangedSignal on the TextBox that I input the text into and store the strings in there, and then whenever a player presses ctrl + z, I first set the textbox's text to the last value of the table, and then delete that last value.

Here is the code that I used (not the exact, the variable are different of course):

local Tab = {};

Box:GetPropertyChangedSignal("Text"):Connect(function()
    Tab[#Tab + 1] = Box.Text;
end);

game:service'Players'.LocalPlayer:GetMouse().KeyDown:Connect(function(key)
    if key == "z" then -- i will add a ctrl check later.
        Box.Text = #Tab > 0 and Tab[#Tab] or "";
        Tab[#Tab] = nil;
    end;
end);

As I mentioned earlier on, I want it to remove whole words at a time. I am thinking of using pattern matching (string.gsub, string.match, %s+, %w+) to remove whole words at a time.

That is as far as I have gotten. Help would be much appreciated.

Aster
  • 3
  • 3
  • Possible duplicate of [Undo/Redo implementation] https://stackoverflow.com/questions/3583901/how-to-design-undo-redo-in-text-editor(https://stackoverflow.com/questions/3541383/undo-redo-implementation) just enter text edit undo implementation into any websearch and you'll find plenty of resources – Piglet Apr 16 '19 at 22:00

1 Answers1

0

Store a list of actions. In order to undo, revert last actions, to redo repeat them. Feel free to merge actions that form a word if you want to undo on word-level only.

H -> append "H"
He -> append "e"
Hel -> append "l"
Helli -> append "i"
Hell -> removeLast "i"
Hello -> append " "
Hello -> append "o"
Hello W -> append "W"

In case it is possible to move the cursor you'll need insert actions where you have to store the position as well.

Another solution would be to store any new word in a table.

{"H"}
{"He"}
{"Hel"}
{"Hell"}
{"Hello"}
{"Hello", " "}
{"Hello", " ", "w"}
{"Hello", " ", "wo"}
{"Hello", " ", "wol"}
{"Hello", " ", "wo"}
{"Hello", " ", "wor"}
{"Hello", " ", "worl"}
{"Hello", " ", "world"}

Start/add a new item for every switch between whitespace and non-whitespace characters. To undo the last word entered, remove it from your list. If you want to undo deletes you'll have to keep a second copy to revert to.

You can also implement linked lists or whatnot. This can become arbitrarily complicated.

Piglet
  • 27,501
  • 3
  • 20
  • 43