ScriptDocument

Mostrar obsoleto

*Este conteúdo é traduzido por IA (Beta) e pode conter erros. Para ver a página em inglês, clique aqui.

Não criável
Não replicado

Uma instância ScriptDocument é um proxy do documento de um Editor de Script do Studio.É diferente do LuaSourceContainer aberto no editor no sentido de representar o estado efêmero de um documento aberto e sua representação está em um formato que é mais adequado para leitura e edição de código do que para sua execução.Em particular, ScriptDocument reflete quaisquer alterações que tenham sido feitas no script aberto no Modo Rascunhos, que a propriedade de origem não tem.

O próprio Editor de Script existe e muda em um subprocesso diferente de qualquer DataModel, então o ScriptDocument replica o Editor de Script aberto, mas não é o editor aberto.Devido à replicação, às vezes há um pequeno atraso entre alterar o texto no editor e atualizar o ScriptDocument.O atraso geralmente ocorre porque o DataModel está ocupado, e é quase sempre extremamente pequeno, mas ainda existe.

A existência de um ScriptDocument indica que um documento está aberto no Editor de Scripts.Todas as instâncias ScriptDocument têm ScriptEditorService como seu pai.Cada instância adere às seguintes convenções de codificação:

  • Todo o texto em ScriptDocument é codificado em UTF-8.
  • Todos os índices de linha são indexados em 1.
  • Todos os índices de personagens são indexados em 1 e contam bytes UTF-8, não grafemas, então a mesma advertência de TextBox.CursorPosition se aplica: muitos personagens de Unicode ocupam mais de um byte.
  • Todos os alcances são inclusivos de sua posição inicial e exclusivos de sua posição final, então start == end implica um alcance vazio.

Todas as APIs para ScriptDocument estão no nível de segurança de Plugin .

Resumo

Métodos

  • GetLine(lineIndex : number?):string
    Segurança do plugin

    Retorna o texto da linha especificada. Quando nenhum argumento é fornecido, retorna a linha da posição do cursor atual.

  • Segurança do plugin

    Retorna o número de linhas no documento.

  • Segurança do plugin

    Retorna a instância subjacente LuaSourceContainer , se existir, caso contrário nil .

  • Segurança do plugin

    Obtém o texto selecionado no editor ou uma string vazia se não houver seleção.

  • Segurança do plugin

    Retorna a última seleção conhecida do Editor de Script no formato: CursorLine, CursorChar, AnchorLine, AnchorChar . Se o Editor de Script não tiver seleção, CursorLine == AnchorLine e CursorChar == AnchorChar .

  • Segurança do plugin

    Obtém o maior da posição do cursor e do âncora. Se o editor não tiver seleção, eles são o mesmo valor.

  • Segurança do plugin

    Obtém o menor da posição do cursor e do âncora. Se o editor não tiver seleção, eles são o mesmo valor.

  • GetText(startLine : number?,startCharacter : number?,endLine : number?,endCharacter : number?):string
    Segurança do plugin

    Retorna texto do editor aberto.

  • Segurança do plugin

    Retorna os números de linha atualmente exibidos na mudança de editor.

  • Segurança do plugin

    Retorna se o editor tem algum texto selecionado ou não.

  • Segurança do plugin

    Retorna verdadeiro se o ScriptDocument representar a barra de comando.

  • Rendimentos
    Segurança do plugin

    Pedidos que o editor associado a este documento fechar. Produz o subprocesso atual até que o editor responda ao solicitar / pedir.

  • EditTextAsync(newText : string,startLine : number,startCharacter : number,endLine : number,endCharacter : number):Tuple
    Rendimentos
    Segurança do plugin

    Substitui o texto no alcance especificado a partir de ( startLine, startColumn ) até ( endLine, endColumn ) com o novo texto.

  • ForceSetSelectionAsync(cursorLine : number,cursorCharacter : number,anchorLine : number?,anchorCharacter : number?):Tuple
    Rendimentos
    Segurança do plugin

    Pede ao editor para definir sua seleção de cursor para os valores de argumento.

  • Rendimentos
    Segurança do plugin
  • RequestSetSelectionAsync(cursorLine : number,cursorCharacter : number,anchorLine : number?,anchorCharacter : number?):Tuple
    Rendimentos
    Segurança do plugin

    Pede ao editor para definir sua seleção de cursor para os valores de argumento.

Eventos

Propriedades

Métodos

GetLine

Segurança do plugin

Parâmetros

lineIndex: number
Valor Padrão: "nil"

Devolução

Amostras de código

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

Segurança do plugin

Devolução

Amostras de código

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
Segurança do plugin

Devolução

Amostras de código

ScriptDocumento:GetScript()

--!noc检查 não
-- Execute o seguinte código na Barra de Comando enquanto um script está aberto
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

Segurança do plugin

Devolução

Amostras de código

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

Segurança do plugin

Devolução

GetSelectionEnd

Segurança do plugin

Devolução

Amostras de código

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

Segurança do plugin

Devolução

Amostras de código

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

Segurança do plugin

Parâmetros

startLine: number
Valor Padrão: "nil"
startCharacter: number
Valor Padrão: "nil"
endLine: number
Valor Padrão: "nil"
endCharacter: number
Valor Padrão: "nil"

Devolução

Amostras de código

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

Segurança do plugin

Devolução

Amostras de código

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

Segurança do plugin

Devolução

Amostras de código

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

Segurança do plugin

Devolução

Amostras de código

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

Rendimentos
Segurança do plugin

Devolução

Amostras de código

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

Rendimentos
Segurança do plugin

Parâmetros

newText: string
Valor Padrão: ""
startLine: number
Valor Padrão: ""
startCharacter: number
Valor Padrão: ""
endLine: number
Valor Padrão: ""
endCharacter: number
Valor Padrão: ""

Devolução

ForceSetSelectionAsync

Rendimentos
Segurança do plugin

Parâmetros

cursorLine: number
Valor Padrão: ""
cursorCharacter: number
Valor Padrão: ""
anchorLine: number
Valor Padrão: "nil"
anchorCharacter: number
Valor Padrão: "nil"

Devolução

Amostras de código

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

Rendimentos
Segurança do plugin

Parâmetros

edits: Array
Valor Padrão: ""

Devolução

RequestSetSelectionAsync

Rendimentos
Segurança do plugin

Parâmetros

cursorLine: number
Valor Padrão: ""
cursorCharacter: number
Valor Padrão: ""
anchorLine: number
Valor Padrão: "nil"
anchorCharacter: number
Valor Padrão: "nil"

Devolução

Amostras de código

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

Eventos

SelectionChanged

Segurança do plugin

Parâmetros

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

Amostras de código

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

Segurança do plugin

Parâmetros

startLine: number
endLine: number

Amostras de código

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)