ScriptDocument
*Este contenido se traduce usando la IA (Beta) y puede contener errores. Para ver esta página en inglés, haz clic en aquí.
Una instancia ScriptDocument es un proxy del documento de un editor de guiones de Studio.Es diferente de la LuaSourceContainer abierta en el editor en que representa el estado efímero de un documento abierto, y su representación está en un formato más adecuado para leer y editar código que para ejecutarlo.En particular, ScriptDocument refleja cualquier cambio que se haya realizado en el script abierto en el modo borradores, que la propiedad de origen no tiene.
El editor de scripts en sí mismo existe y cambia en un subproceso diferente a cualquier DataModel, por lo que el ScriptDocument replica el Editor de scriptsabierto, pero no es el editor abierto.Debido a la replicación, a veces hay un ligero retraso entre cambiar el texto en el editor y actualizar el ScriptDocument .El retraso suele ocurrir porque el DataModel está ocupado, y casi siempre es extremadamente pequeño, pero aún existe.
La existencia de un ScriptDocument indica que un documento está abierto en el editor de scripts.Todas las instancias ScriptDocument tienen ScriptEditorService como padre.Cada instancia se adhiere a las siguientes convenciones de codificación:
- Todo el texto en ScriptDocument está codificado en UTF-8.
- Todos los índices de línea están indexados en 1.
- Todos los índices de personajes están indexados en 1 y cuentan bytes UTF-8, no grafemas, por lo que se aplica la misma advertencia de TextBox.CursorPosition : muchos personajes de Unicode toman más de un byte.
- Todos los rangos son inclusivos de su posición de inicio y exclusivos de su posición final, por lo que start == end implica un rango vacío.
Todas las API para ScriptDocument están en el nivel de seguridad de plugin .
Resumen
Métodos
Devuelve el texto de la línea especificada. Cuando no se proporciona ningún argumento, devuelve la línea de la posición del cursor actual.
Devuelve el número de líneas en el documento.
Devuelve la instancia subyacente LuaSourceContainer si existe, de lo contrario nil .
Obtiene el texto seleccionado en el editor o una cadena vacía si no hay selección.
Devuelve la última selección conocida del editor de scripts en el formato: CursorLine, CursorChar, AnchorLine, AnchorChar . Si el editor de scripts no tiene selección, CursorLine == AnchorLine y CursorChar == AnchorChar .
Obtiene el mayor de la posición del cursor y el ancla. Si el editor no tiene selección, son el mismo valor.
Obtiene el menor de la posición del cursor y el ancla. Si el editor no tiene selección, son el mismo valor.
- GetText(startLine : number?,startCharacter : number?,endLine : number?,endCharacter : number?):string
Devuelve texto del editor abierto.
Devuelve los números de línea actualmente mostrados en el cambio de editor.
Devuelve si el editor tiene o no algún texto seleccionado.
Devuelve verdadero si el ScriptDocument representa la barra de comandos.
Solicitudes que el editor asociado con este documento cerrar. Produce el hilo actual hasta que el editor responda a la solicitud.
- EditTextAsync(newText : string,startLine : number,startCharacter : number,endLine : number,endCharacter : number):Tuple
Reemplaza el texto en el rango especificado desde ( startLine , startColumn ) hasta ( endLine , endColumn ) con nuevo texto.
- ForceSetSelectionAsync(cursorLine : number,cursorCharacter : number,anchorLine : number?,anchorCharacter : number?):Tuple
Pide al editor que establezca la selección del cursor en los valores de los argumentos.
- RequestSetSelectionAsync(cursorLine : number,cursorCharacter : number,anchorLine : number?,anchorCharacter : number?):Tuple
Pide al editor que establezca la selección del cursor en los valores de los argumentos.
Eventos
- SelectionChanged(positionLine : number,positionCharacter : number,anchorLine : number,anchorCharacter : number):RBXScriptSignal
Se activa cuando el ScriptDocument cambia, incluido inmediatamente después de un cambio de texto.
Se activa cuando los números de línea mostrados en el editor cambian.
Propiedades
Métodos
GetLine
Devuelve el texto de la línea especificada. Cuando no se proporciona ningún argumento, devuelve la línea de la posición del cursor actual.
Parámetros
Devuelve
Muestras 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
Devuelve el número de líneas en el documento activo.
Devuelve
Muestras 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
GetScript
Devuelve la instancia subyacente LuaSourceContainer si existe, de lo contrario nil .
Devuelve
Muestras de código
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
Obtiene el texto seleccionado en el editor o una cadena vacía si no hay selección.
Devuelve
Muestras 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
Devuelve la última selección conocida del editor de scripts en el formato: CursorLine, CursorChar, AnchorLine, AnchorChar . Si el editor de scripts no tiene selección, CursorLine == AnchorLine y CursorChar == AnchorChar .
Devuelve
CursorLine, CursorChar, Línea de anclaje, AnchorChar.
GetSelectionEnd
Obtiene el mayor de la posición del cursor y el ancla. Si el editor no tiene selección, son el mismo valor.
Devuelve
Muestras 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
Obtiene el menor de la posición del cursor y el ancla. Si el editor no tiene selección, son el mismo valor.
Devuelve
Muestras 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
Devuelve texto del editor abierto. Debe llamarse con 0, 2 o 4 argumentos:
- Si se llama con 0 argumentos, obtiene todo el contenido del editor abierto.
- Si se llama con 2 argumentos, obtiene el texto del documento que comienza en ( startLine , startColumn ).
- Si se llama con 4 argumentos, obtiene el texto del documento que comienza en ( startLine , startColumn ) y termina en ( endLine , endColumn ).
Parámetros
Devuelve
Muestras 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
Devuelve los números de línea actualmente mostrados en el cambio de editor.El editor muestra las líneas entre startLine y endLine, incluidas.La primera y última línea solo se mostrarán parcialmente.Por ejemplo, solo el píxel superior de la última línea podría estar en la pantalla.Además, el plegado de código puede ocultar líneas entre startLine y endLine.
Devuelve
Muestras 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
Devuelve si el editor tiene o no algún texto seleccionado.
Devuelve
Muestras 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
Devuelve verdadero si el ScriptDocument representa la barra de comandos. La barra de comandos tiene reglas y limitaciones especiales en esta API:
- Studio crea la barra de comandos antes de ejecutar los plugins, por lo que no siempre dispara el evento abierto, aunque cierra y se reabre como Studio transita entre modelos de datos.
- No puedes editar la barra de comandos con EditTextAsync por razones de seguridad.
Devuelve
Muestras 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
Solicitudes que el editor asociado con este documento cerrar.Devuelve el hilo actual hasta que el editor responda a la solicitud.Si la función tiene éxito, devuelve (verdadero, nulo).Si la función falla, devuelve (false, cadena) como una descripción del problema.
Esta función no puede cerrar la barra de comandos.
Devuelve
Muestras 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
Reemplaza el texto en el rango especificado desde ( startLine , startColumn ) hasta ( endLine , endColumn ) con newText .Si el rango está vacío, entonces la función inserta el texto en ( startLine , startColumn ).Si el cursor de texto está dentro del rango especificado, el cursor se mueve a la posición final de la editar.Si no, el cursor de texto no se herramienta de movimiento.Esta función devuelve el hilo actual hasta que reciba una respuesta del editor sobre la editar.
Si la función tiene éxito, devuelve ( true , nil ).
La función lanza un error si:
- El rango no es no válido.
- El rango cortaría un carácter de idioma, por ejemplo, reemplazaría solo algunos de los bytes del carácter de idioma.
- El propio newText contiene UTF-8 inválido.
Si la función falla, devuelve (false, string).La cadena es una descripción del problema.El tipo de fallo más común es un desajuste de versión.Esto ocurre cuando intentas llamar a EditTextAsync durante el tiempo en que el ScriptDocument está desincronizado con el contenido del editor.Si esto sucede, puedes volver a intentar editar.
Parámetros
Devuelve
ForceSetSelectionAsync
Pide al editor que establezca la selección del cursor en los valores de los argumentos.Se deben pasar ambos argumentos de anclaje o ninguno.Si ninguno se pasa, entonces cada uno predeterminado será el mismo que el argumento del cursor correspondiente.El editor podría rechazar actualizar su cursor si el contenido del texto del documento ha cambiado.A diferencia de ScriptDocument:RequestSetSelectionAsync(), el editor no rechazará mover su cursor si el cursor se ha movido desde que se hizo la solicitud.Devuelve (verdadero, nulo) si el cursor se actualizó, y (falso, cadena) con una cadena de explicación si no lo fue.Produce el hilo actual hasta que el editor responda.
Parámetros
Devuelve
Muestras 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
RequestSetSelectionAsync
Pide al editor que establezca la selección del cursor en los valores de los argumentos.Se deben pasar ambos argumentos de anclaje o ninguno.Si ninguno se pasa, entonces cada uno predeterminado será el mismo que el argumento del cursor correspondiente.El editor podría rechazar actualizar su cursor si el contenido del texto del documento ha cambiado o el cursor se ha movido desde que se hizo la solicitud.Devuelve (verdadero, nulo) si el cursor se actualizó, y (falso, cadena) con una cadena de explicación si no lo fue.Produce el hilo actual hasta que el editor responda.
Parámetros
Devuelve
Muestras 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
Se activa cuando el ScriptDocument cambia, incluido inmediatamente después de un cambio de texto.
Parámetros
Muestras 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
Se enciende cuando los números de línea mostrados en el editor cambian. Vea ScriptDocument.GetViewport para más detalles.
Parámetros
Muestras de código
Demonstrates using ScriptDocument.ViewportChanged to print the start and end line of the script's viewport when it changes.
To run:
- Ensure Output view is open
- Run the below code in the Command Bar
- Scroll up and down in the opened Script window
--!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)