Let’s assume you want to autocomplete when you press the TAB key, similar to in Linux (this could interfere with the text in the box, so I recommend using another key, I just use this as an example).
You can use the ContextActionService
to bind and unbind an action on the tab key based on the TextBox.Focused
and TextBox.FocusLost
events, as mentioned above. The event bound to the TAB key will be our search function for the player.
For our search function, firstly we need to get the players using Game.Players:GetPlayers()
. This returns a table of player instances. We can then search through their names.
So, when the user presses TAB (or whatever you choose), we get the players like this and dump them in a local table. Now, we get the current text of the TextBox, using TextBoxName.Text
, also stored in a local variable.
Finally, we need a table of found matches, which should start empty.
Now, we can loop through the player instances searching for a match with the text we obtained.
We can use find and sub for this, as it returns an index on a successful match, and nil on an unsuccessful match. First, extract a sub string with sub so that we only search from the start to the end. Go from the beginning of the string, to the length of the TextBox text.
Next, run a find on it, if it does not return nil
, the function found a match. Now, append it to the end of the array of matches.
Finally, for our result. If the table of matches found more than one, there are multiple possible players, and we should do nothing. Return from the callback if this is true. However, if we found just one, we can set the text of the TextBox to the name of the player we found.
Your code would look something like this:
function findUser()
local players = game.Players:GetPlayers()
local text = NameOfTextBox.Text
local matches = {}
for i, Player in ipairs(players) do
local name = Player.Name
local term = string.sub(name, 1, string.len(text))
local match = string.find(term, text)
if match then
table.insert(matches, name)
end
end
-- If we don’t have multiple matches , do stuff
if not #matches > 1 then
NameOfTextBox.Text = matches[1]
end
end
There are of course other things you can do with this, it’s just an example. Play around with it and tell me how you get on.