ScriptDocument
*Este conteúdo é traduzido por IA (Beta) e pode conter erros. Para ver a página em inglês, clique aqui.
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
Retorna o texto da linha especificada. Quando nenhum argumento é fornecido, retorna a linha da posição do cursor atual.
Retorna o número de linhas no documento.
Retorna a instância subjacente LuaSourceContainer , se existir, caso contrário nil .
Obtém o texto selecionado no editor ou uma string vazia se não houver seleção.
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 .
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.
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
Retorna texto do editor aberto.
Retorna os números de linha atualmente exibidos na mudança de editor.
Retorna se o editor tem algum texto selecionado ou não.
Retorna verdadeiro se o ScriptDocument representar a barra de comando.
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
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
Pede ao editor para definir sua seleção de cursor para os valores de argumento.
- RequestSetSelectionAsync(cursorLine : number,cursorCharacter : number,anchorLine : number?,anchorCharacter : number?):Tuple
Pede ao editor para definir sua seleção de cursor para os valores de argumento.
Eventos
- SelectionChanged(positionLine : number,positionCharacter : number,anchorLine : number,anchorCharacter : number):RBXScriptSignal
Incêndios quando o ScriptDocument muda, incluindo imediatamente após uma alteração de texto.
Dispara quando os números de linha exibidos no editor mudam.
Propriedades
Métodos
GetLine
Parâmetros
Devolução
Amostras de código
--!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
Devolução
Amostras de código
--!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
GetScript
Devolução
Amostras de código
--!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
Devolução
Amostras de código
--!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
GetSelectionEnd
Devolução
Amostras de código
--!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
Devolução
Amostras de código
--!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
Parâmetros
Devolução
Amostras de código
--!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
Devolução
Amostras de código
--!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
Devolução
Amostras de código
--!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
Devolução
Amostras de código
--!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
Devolução
Amostras de código
--!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
Parâmetros
Devolução
ForceSetSelectionAsync
Parâmetros
Devolução
Amostras de código
--!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
RequestSetSelectionAsync
Parâmetros
Devolução
Amostras de código
--!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
Parâmetros
Amostras de código
--!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
Parâmetros
Amostras de código
--!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)