PcoWSkbVqDnWTu_dm2ix
Collapse Sidebar

CursorPosition

TextBox

int

CursorPosition determines the offset of the text cursor in bytes, or -1 if the TextBox is not currently being edited. A value of 1 represents the beginning, the position before the first byte in the TextBox/Text|Text property. When used in conjunction with the TextBox/SelectionStart|SelectionStart property, it is possible to both get and set selected text within a TextBox.

A visual explanation of how CursorPosition works

It should be noted that the units of this property is bytes and that many unicode characters such as emoji are longer than 1 byte. For instance, if a player types into the TextBox “Hello👋” – “Hello” immediately followed by the waving hand sign – the cursor position would be 10, not 7, since the emoji uses 4 bytes.


Code Samples


TextBox Selections

This code sample demonstrates reading the current selection of a TextBox using TextBox/CursorPosition|CursorPosition and TextBox/SelectionStart|SelectionStart.

local textBox = script.Parent

local function showSelection()
	if textBox.CursorPosition == -1 or textBox.SelectionStart == -1 then
		print("No selection")
	else
		local selectedText = string.sub(
			textBox.Text,
			math.min(textBox.CursorPosition, textBox.SelectionStart),
			math.max(textBox.CursorPosition, textBox.SelectionStart)
		)
		print("The selection is: \"" .. selectedText .. "\"")
	end
end

textBox:GetPropertyChangedSignal("CursorPosition"):Connect(showSelection)
textBox:GetPropertyChangedSignal("SelectionStart"):Connect(showSelection)