ScriptDocument

Afficher les obsolètes
Création impossible
Non répliqué

A ScriptDocument instance is a proxy of the document of a Studio Script Editor. It's different from the LuaSourceContainer open in the editor in that it represents the ephemeral state of an open document, and its representation is in a format that's more suited for reading and editing code than executing it. In particular, ScriptDocument reflects any changes that have been made to the open script in Drafts Mode, which the source property doesn't.

The Script Editor itself exists and changes on a different thread than any DataModel, so the ScriptDocument replicates the open Script Editor, but it isn't the open editor. Because of the replication, there's sometimes a slight delay between changing the text in the editor and updating the ScriptDocument. The delay usually occurs because the DataModel is busy, and it's almost always extremely small, but it still exists.

The existence of a ScriptDocument indicates that a document is open in the Script Editor. All ScriptDocument instances have ScriptEditorService as its parent. Each instance adheres to the following encoding conventions:

  • All text in ScriptDocument is UTF-8 encoded.
  • All line indices are 1-indexed.
  • All character indices are 1-indexed and count UTF-8 bytes, not graphemes, so the same warning from TextBox.CursorPosition applies: many Unicode characters take more than one byte.
  • All ranges are inclusive of their start position and exclusive of their end position, so start == end implies an empty range.

All APIs for ScriptDocument are at Plugin level security.

Résumé

Méthodes

  • GetLine(lineIndex : number?):string
    Sécurité des plugins

    Returns the text of the specified line. When no argument is provided, returns the line of the current cursor position.

  • Sécurité des plugins

    Returns the number of lines in the document.

  • Sécurité des plugins

    Returns the underlying LuaSourceContainer instance, if one exists, otherwise nil.

  • Sécurité des plugins

    Gets the text selected in the editor, or an empty string if there is no selection.

  • Sécurité des plugins

    Returns the last known selection of the Script Editor in the format: CursorLine, CursorChar, AnchorLine, AnchorChar. If the Script Editor has no selection, CursorLine == AnchorLine and CursorChar == AnchorChar.

  • Sécurité des plugins

    Gets the larger of the cursor position and anchor. If the editor has no selection, they are the same value.

  • Sécurité des plugins

    Gets the smaller of the cursor position and anchor. If the editor has no selection, they are the same value.

  • GetText(startLine : number?,startCharacter : number?,endLine : number?,endCharacter : number?):string
    Sécurité des plugins

    Returns text from the open editor.

  • Sécurité des plugins

    Returns the currently displayed line numbers in the editor change.

  • Sécurité des plugins

    Returns whether or not the editor has any text selected.

  • Sécurité des plugins

    Returns true if the ScriptDocument represents the Command bar.

  • Rendement
    Sécurité des plugins

    Requests that the editor associated with this document close. Yields the current thread until the editor responds to the request.

  • EditTextAsync(newText : string,startLine : number,startCharacter : number,endLine : number,endCharacter : number):Tuple
    Rendement
    Sécurité des plugins

    Replaces the text in the specified range from (startLine, startColumn) to (endLine, endColumn) with newText.

  • ForceSetSelectionAsync(cursorLine : number,cursorCharacter : number,anchorLine : number?,anchorCharacter : number?):Tuple
    Rendement
    Sécurité des plugins

    Asks the editor to set its cursor selection to the argument values.

  • Rendement
    Sécurité des plugins
  • RequestSetSelectionAsync(cursorLine : number,cursorCharacter : number,anchorLine : number?,anchorCharacter : number?):Tuple
    Rendement
    Sécurité des plugins

    Asks the editor to set its cursor selection to the argument values.

Évènements

Propriétés

Méthodes

GetLine

Sécurité des plugins

Returns the text of the specified line. When no argument is provided, returns the line of the current cursor position.

Paramètres

lineIndex: number
Valeur par défaut : "nil"

Retours

Échantillons de code

ScriptDocument.SelectionChanged and ScriptDocument:GetLine()

--!nocheck
-- Run the following code in the Command Bar while a script is open
local ScriptEditorService = game:GetService("ScriptEditorService")
local function getFirstOpenDocument()
local documents = ScriptEditorService:GetScriptDocuments()
for _, document in documents do
if not document:IsCommandBar() then
return document
end
end
return nil
end
local scriptDocument = getFirstOpenDocument()
if scriptDocument then
scriptDocument.SelectionChanged:Connect(function(positionLine, positionCharacter, anchorLine, anchorCharacter)
print(`Selected: Line {positionLine}, Char {positionCharacter}`)
print(`Anchor: Line {anchorLine}, Char {anchorCharacter}`)
local lineText = scriptDocument:GetLine(positionLine)
print(`Selected line text: {lineText}`)
end)
else
print("No scripts open")
end

GetLineCount

Sécurité des plugins

Returns the number of lines in the active document.


Retours

Échantillons de code

ScriptDocument:GetLineCount()

--!nocheck
-- Run the following code in the Command Bar while a script is open
local ScriptEditorService = game:GetService("ScriptEditorService")
local function getFirstOpenDocument()
local documents = ScriptEditorService:GetScriptDocuments()
for _, document in documents do
if not document:IsCommandBar() then
return document
end
end
return nil
end
local scriptDocument = getFirstOpenDocument()
if scriptDocument then
local lineCount = scriptDocument:GetLineCount()
print(`The script has {lineCount} lines!`)
else
print("No scripts open")
end
Sécurité des plugins

Returns the underlying LuaSourceContainer instance, if one exists, otherwise nil.


Retours

Échantillons de code

ScriptDocument:GetScript()

--!nocheck
-- Run the following code in the Command Bar while a script is open
local ScriptEditorService = game:GetService("ScriptEditorService")
local function getFirstOpenDocument()
local documents = ScriptEditorService:GetScriptDocuments()
for _, document in documents do
if not document:IsCommandBar() then
return document
end
end
return nil
end
local scriptDocument = getFirstOpenDocument()
if scriptDocument then
local openScript = scriptDocument:GetScript()
print(`Currently open script: {openScript:GetFullName()}`)
else
print("No scripts open")
end

GetSelectedText

Sécurité des plugins

Gets the text selected in the editor, or an empty string if there is no selection.


Retours

Échantillons de code

ScriptDocument:HasSelectedText() and :GetSelectedText()

--!nocheck
-- Run the following code in the Command Bar while a script is open
local ScriptEditorService = game:GetService("ScriptEditorService")
local function getFirstOpenDocument()
local documents = ScriptEditorService:GetScriptDocuments()
for _, document in documents do
if not document:IsCommandBar() then
return document
end
end
return nil
end
local scriptDocument = getFirstOpenDocument()
if scriptDocument then
scriptDocument.SelectionChanged:Connect(function()
if scriptDocument:HasSelectedText() then
local selectedText = scriptDocument:GetSelectedText()
print(`Currently selected text: {selectedText}`)
else
print("No text currently selected")
end
end)
else
print("No scripts open")
end

GetSelection

Sécurité des plugins

Returns the last known selection of the Script Editor in the format: CursorLine, CursorChar, AnchorLine, AnchorChar. If the Script Editor has no selection, CursorLine == AnchorLine and CursorChar == AnchorChar.


Retours

CursorLine, CursorChar, AnchorLine, AnchorChar.

GetSelectionEnd

Sécurité des plugins

Gets the larger of the cursor position and anchor. If the editor has no selection, they are the same value.


Retours

Échantillons de code

ScriptDocument:GetSelectionStart() and :GetSelectionEnd()

--!nocheck
-- Run the following code in the Command Bar while a script is open
local ScriptEditorService = game:GetService("ScriptEditorService")
local function getFirstOpenDocument()
local documents = ScriptEditorService:GetScriptDocuments()
for _, document in documents do
if not document:IsCommandBar() then
return document
end
end
return nil
end
local scriptDocument = getFirstOpenDocument()
if scriptDocument then
local startLine, startCharacter = scriptDocument:GetSelectionStart()
local endLine, endCharacter = scriptDocument:GetSelectionEnd()
print(`Selection start: Line {startLine}, Char {startCharacter}`)
print(`Selection end: Line {endLine}, Char {endCharacter}`)
else
print("No scripts open")
end

GetSelectionStart

Sécurité des plugins

Gets the smaller of the cursor position and anchor. If the editor has no selection, they are the same value.


Retours

Échantillons de code

ScriptDocument:GetSelectionStart() and :GetSelectionEnd()

--!nocheck
-- Run the following code in the Command Bar while a script is open
local ScriptEditorService = game:GetService("ScriptEditorService")
local function getFirstOpenDocument()
local documents = ScriptEditorService:GetScriptDocuments()
for _, document in documents do
if not document:IsCommandBar() then
return document
end
end
return nil
end
local scriptDocument = getFirstOpenDocument()
if scriptDocument then
local startLine, startCharacter = scriptDocument:GetSelectionStart()
local endLine, endCharacter = scriptDocument:GetSelectionEnd()
print(`Selection start: Line {startLine}, Char {startCharacter}`)
print(`Selection end: Line {endLine}, Char {endCharacter}`)
else
print("No scripts open")
end

GetText

Sécurité des plugins

Returns text from the open editor. Must be called with 0, 2 or 4 arguments:

  • If called with 0 arguments, gets the entire contents of the open editor.
  • If called with 2 arguments, gets the text of the document starting at (startLine, startColumn).
  • If called with 4 arguments, gets the text of the document starting at (startLine, startColumn) and ending at (endLine, endColumn).

Paramètres

startLine: number
Valeur par défaut : "nil"
startCharacter: number
Valeur par défaut : "nil"
endLine: number
Valeur par défaut : "nil"
endCharacter: number
Valeur par défaut : "nil"

Retours

Échantillons de code

ScriptDocument:GetText()

--!nocheck
-- Run the following code in the Command Bar while a script is open
local ScriptEditorService = game:GetService("ScriptEditorService")
local function getFirstOpenDocument()
local documents = ScriptEditorService:GetScriptDocuments()
for _, document in documents do
if not document:IsCommandBar() then
return document
end
end
return nil
end
local scriptDocument = getFirstOpenDocument()
if scriptDocument then
local text = scriptDocument:GetText()
print(`Script contents: {text}`)
else
print("No scripts open")
end

GetViewport

Sécurité des plugins

Returns the currently displayed line numbers in the editor change. The editor displays the lines between startLine and endLine, inclusive. The first and last line might only display partially. For example, only the topmost pixel of the last line might be on screen. Furthermore, code folding might hide lines between startLine and endLine.


Retours

Échantillons de code

ScriptDocument:GetViewport

--!nocheck
-- Run the following code in the Command Bar while a script is open
local ScriptEditorService = game:GetService("ScriptEditorService")
local function getFirstOpenDocument()
local documents = ScriptEditorService:GetScriptDocuments()
for _, document in documents do
if not document:IsCommandBar() then
return document
end
end
return nil
end
local scriptDocument = getFirstOpenDocument()
if scriptDocument then
local firstLine, lastLine = scriptDocument:GetViewport()
print(`Currently viewing lines {firstLine} to {lastLine}`)
else
print("No scripts open")
end

HasSelectedText

Sécurité des plugins

Returns whether or not the editor has any text selected.


Retours

Échantillons de code

ScriptDocument:HasSelectedText() and :GetSelectedText()

--!nocheck
-- Run the following code in the Command Bar while a script is open
local ScriptEditorService = game:GetService("ScriptEditorService")
local function getFirstOpenDocument()
local documents = ScriptEditorService:GetScriptDocuments()
for _, document in documents do
if not document:IsCommandBar() then
return document
end
end
return nil
end
local scriptDocument = getFirstOpenDocument()
if scriptDocument then
scriptDocument.SelectionChanged:Connect(function()
if scriptDocument:HasSelectedText() then
local selectedText = scriptDocument:GetSelectedText()
print(`Currently selected text: {selectedText}`)
else
print("No text currently selected")
end
end)
else
print("No scripts open")
end

IsCommandBar

Sécurité des plugins

Returns true if the ScriptDocument represents the Command bar. The command bar has special rules and limitations in this API:

  • Studio creates the Command bar before running plugins, so it doesn't always fire the opened event, although it does close and reopen as Studio transitions between DataModels.
  • You can't edit the Command bar with EditTextAsync for security reasons.

Retours

Échantillons de code

ScriptDocument:IsCommandBar()

--!nocheck
-- Run the following code in the Command Bar
local ScriptEditorService = game:GetService("ScriptEditorService")
local documents = ScriptEditorService:GetScriptDocuments()
for _, document in documents do
if document:IsCommandBar() then
print("Command bar document:", document)
end
end

CloseAsync

Rendement
Sécurité des plugins

Requests that the editor associated with this document close. Yields the current thread until the editor responds to the request. If the function succeeds, it returns (true, nil). If the function fails, it returns (false, string) as a description of the problem.

This function can't close the command bar.


Retours

Échantillons de code

ScriptDocument:CloseAsync

--!nocheck
-- Run the following code in the Command Bar
local ScriptEditorService = game:GetService("ScriptEditorService")
local documents = ScriptEditorService:GetScriptDocuments()
local scriptDocument
-- Find the first open script document
for _, document in documents do
-- The Command Bar can't be closed, so don't select it
if not document:IsCommandBar() then
scriptDocument = document
break
end
end
if scriptDocument then
local success, err = scriptDocument:CloseAsync()
if success then
print(`Closed {scriptDocument.Name}`)
else
warn(`Failed to close {scriptDocument.Name} because: {err}`)
end
else
print("No open scripts")
end

EditTextAsync

Rendement
Sécurité des plugins

Replaces the text in the specified range from (startLine, startColumn) to (endLine, endColumn) with newText. If the range is empty, then the function inserts the text at (startLine, startColumn). If the text cursor is within the specified range, the cursor moves to the end position of the edit. Otherwise, the text cursor doesn't move. This function yields the current thread until it receives a reply from the editor about the edit.

If the function succeeds, it returns (true, nil).

The function throws an error if:

  • The range is invalid.
  • The range would slice a unicode character, for example replace only some of the bytes of the unicode character.
  • The newText itself contains invalid UTF-8.

If the function fails, it returns (false, string). The string is a description of the problem. The most common failure type is a version mismatch. This occurs when you try to call EditTextAsync during the time when the ScriptDocument is out of sync with the contents of the editor. If this happens, you can retry the edit.

Paramètres

newText: string
startLine: number
startCharacter: number
endLine: number
endCharacter: number

Retours

ForceSetSelectionAsync

Rendement
Sécurité des plugins

Asks the editor to set its cursor selection to the argument values. Both anchor arguments must be passed, or neither. If neither is passed, then they each default to being the same as the corresponding cursor argument. The editor might decline to update its cursor if the text content of the document has changed. Unlike ScriptDocument:RequestSetSelectionAsync(), the editor will not decline to move its cursor if the cursor has moved since the request was made. Returns (true, nil) if the cursor was updated, and (false, string) with an explanation string if it was not. Yields the current thread until the editor replies.

Paramètres

cursorLine: number
cursorCharacter: number
anchorLine: number
Valeur par défaut : "nil"
anchorCharacter: number
Valeur par défaut : "nil"

Retours

Échantillons de code

ScriptDocument:ForceSetSelectionAsync()

--!nocheck
-- Run the following code in the Command Bar while a script is open
local ScriptEditorService = game:GetService("ScriptEditorService")
local function getFirstOpenDocument()
local documents = ScriptEditorService:GetScriptDocuments()
for _, document in documents do
if not document:IsCommandBar() then
return document
end
end
return nil
end
local scriptDocument = getFirstOpenDocument()
if scriptDocument then
-- Get the text on the cursor's current line
local cursorLine = scriptDocument:GetSelection()
local lineText = scriptDocument:GetLine(cursorLine)
-- Force select the entire line of text
local success, err = scriptDocument:ForceSetSelectionAsync(cursorLine, 1, cursorLine, #lineText + 1)
if success then
print("Set selection!")
else
print(`Failed to set selection because: {err}`)
end
else
print("No scripts open")
end

MultiEditTextAsync

Rendement
Sécurité des plugins

Paramètres

edits: Array

Retours

RequestSetSelectionAsync

Rendement
Sécurité des plugins

Asks the editor to set its cursor selection to the argument values. Both anchor arguments must be passed, or neither. If neither is passed, then they each default to being the same as the corresponding cursor argument. The editor might decline to update its cursor if the text content of the document has changed, or the cursor has moved since the request was made. Returns (true, nil) if the cursor was updated, and (false, string) with an explanation string if it was not. Yields the current thread until the editor replies.

Paramètres

cursorLine: number
cursorCharacter: number
anchorLine: number
Valeur par défaut : "nil"
anchorCharacter: number
Valeur par défaut : "nil"

Retours

Échantillons de code

ScriptDocument:RequestSetSelectionAsync()

--!nocheck
-- Run the following code in the Command Bar while a script is open
local ScriptEditorService = game:GetService("ScriptEditorService")
local function getFirstOpenDocument()
local documents = ScriptEditorService:GetScriptDocuments()
for _, document in documents do
if not document:IsCommandBar() then
return document
end
end
return nil
end
local scriptDocument = getFirstOpenDocument()
if scriptDocument then
-- Get the text on the cursor's current line
local cursorLine = scriptDocument:GetSelection()
local lineText = scriptDocument:GetLine(cursorLine)
-- Force select the entire line of text
local success, err = scriptDocument:RequestSetSelectionAsync(cursorLine, 1, cursorLine, #lineText + 1)
if success then
print("Set selection!")
else
print(`Failed to set selection because: {err}`)
end
else
print("No scripts open")
end

Évènements

SelectionChanged

Sécurité des plugins

Fires when the ScriptDocument changes, including immediately after a text change.

Paramètres

positionLine: number
positionCharacter: number
anchorLine: number
anchorCharacter: number

Échantillons de code

ScriptDocument.SelectionChanged and ScriptDocument:GetLine()

--!nocheck
-- Run the following code in the Command Bar while a script is open
local ScriptEditorService = game:GetService("ScriptEditorService")
local function getFirstOpenDocument()
local documents = ScriptEditorService:GetScriptDocuments()
for _, document in documents do
if not document:IsCommandBar() then
return document
end
end
return nil
end
local scriptDocument = getFirstOpenDocument()
if scriptDocument then
scriptDocument.SelectionChanged:Connect(function(positionLine, positionCharacter, anchorLine, anchorCharacter)
print(`Selected: Line {positionLine}, Char {positionCharacter}`)
print(`Anchor: Line {anchorLine}, Char {anchorCharacter}`)
local lineText = scriptDocument:GetLine(positionLine)
print(`Selected line text: {lineText}`)
end)
else
print("No scripts open")
end

ViewportChanged

Sécurité des plugins

Fires when the displayed line numbers in the editor change. See ScriptDocument.GetViewport for details.

Paramètres

startLine: number
endLine: number

Échantillons de code

Connecting to ScriptDocument.ViewportChanged

--!nocheck
--[[
To run:
1. Ensure Output view is open
2. Run the below code in the Command Bar
3. Scroll up and down in the opened Script window
Print statements from the ViewportChanged event will appear in the Output
]]
local Workspace = game:GetService("Workspace")
local ScriptEditorService = game:GetService("ScriptEditorService")
-- Create text that spans many lines
local dummyText = string.rep("-- Dummy Text\n", 60)
-- Create a script containing the dummy text and open it
local otherScript = Instance.new("Script")
otherScript.Source = dummyText
otherScript.Parent = Workspace
local success, err = ScriptEditorService:OpenScriptDocumentAsync(otherScript)
if not success then
warn(`Failed to open script because: {err}`)
return
end
-- Get a reference to the opened script
local scriptDocument = ScriptEditorService:FindScriptDocument(otherScript)
local function onViewportChanged(startLine: number, endLine: number)
print(`Script Viewport Changed - startLine: {startLine}, endLine: {endLine}`)
end
-- Connect the ViewportChanged event to the function above that prints the start and end line of the updated viewport
scriptDocument.ViewportChanged:Connect(onViewportChanged)