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 de ScriptDocument es un proxy del documento de un Editor de Scripts de Studio. Es diferente del LuaSourceContainer abierto 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 Modo de Borrador, lo cual la propiedad source no hace.
El Editor de Scripts en sí existe y cambia en un hilo diferente a cualquier DataModel, por lo que ScriptDocument replica el Editor de Scripts abierto, pero no es el editor abierto. Debido a la replicación, a veces hay un ligero retraso entre el cambio de texto en el editor y la actualización del ScriptDocument. El retraso generalmente ocurre porque el DataModel está ocupado, y casi siempre es extremadamente pequeño, pero aún así existe.
La existencia de un ScriptDocument indica que hay un documento abierto en el Editor de Scripts. Todas las instancias de ScriptDocument tienen a ScriptEditorService como su 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 son 1-indexados.
- Todos los índices de carácter son 1-indexados y cuentan bytes UTF-8, no grafemas, por lo que se aplica la misma advertencia de TextBox.CursorPosition: muchos caracteres Unicode ocupan más de un byte.
- Todos los rangos son inclusivos de su posición de inicio y exclusivos de su posición de fin, así que inicio == fin implica un rango vacío.
Todas las APIs para ScriptDocument están en un nivel de seguridad de Plugin.
Resumen
Métodos
Solicita que el editor asociado con este documento se cierre. Cede 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 de (startLine, startColumn) a (endLine, endColumn) con newText.
- ForceSetSelectionAsync(cursorLine : number,cursorCharacter : number,anchorLine : number?,anchorCharacter : number?):Tuple
Pide al editor que establezca su selección de cursor a los valores de argumento.
Devuelve el texto de la línea especificada. Cuando no se proporciona ningún argumento, devuelve la línea de la posición actual del cursor.
Devuelve el número de líneas en el documento.
Devuelve la instancia subyacente de 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 anclaje. Si el editor no tiene selección, son el mismo valor.
Obtiene el menor de la posición del cursor y el anclaje. 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 del editor.
Devuelve si el editor tiene algún texto seleccionado o no.
Devuelve verdadero si el ScriptDocument representa la barra de comandos.
- RequestSetSelectionAsync(cursorLine : number,cursorCharacter : number,anchorLine : number?,anchorCharacter : number?):Tuple
Pide al editor que establezca su selección de cursor a los valores de argumento.
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
CloseAsync
Devuelve
Muestras de código
--!nocheck
-- Ejecuta el siguiente código en la Barra de Comandos
local ScriptEditorService = game:GetService("ScriptEditorService")
local documents = ScriptEditorService:GetScriptDocuments()
local scriptDocument
-- Encuentra el primer documento de script abierto
for _, document in documents do
-- La Barra de Comandos no se puede cerrar, así que no la selecciones
if not document:IsCommandBar() then
scriptDocument = document
break
end
end
if scriptDocument then
local success, err = scriptDocument:CloseAsync()
if success then
print(`Cerrado {scriptDocument.Name}`)
else
warn(`No se pudo cerrar {scriptDocument.Name} porque: {err}`)
end
else
print("No hay scripts abiertos")
end
EditTextAsync
Parámetros
Devuelve
ForceSetSelectionAsync
Parámetros
Devuelve
Muestras de código
--!nocheck
-- Ejecuta el siguiente código en la barra de comandos mientras un script está abierto
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
-- Obtener el texto en la línea actual del cursor
local cursorLine = scriptDocument:GetSelection()
local lineText = scriptDocument:GetLine(cursorLine)
-- Seleccionar forzadamente toda la línea de texto
local success, err = scriptDocument:ForceSetSelectionAsync(cursorLine, 1, cursorLine, #lineText + 1)
if success then
print("¡Selección establecida!")
else
print(`Error al establecer la selección porque: {err}`)
end
else
print("No hay scripts abiertos")
end
GetLine
Parámetros
Devuelve
Muestras de código
--!nocheck
-- Ejecuta el siguiente código en la Barra de Comandos mientras un script está abierto
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(`Seleccionado: Línea {positionLine}, Carácter {positionCharacter}`)
print(`Ancla: Línea {anchorLine}, Carácter {anchorCharacter}`)
local lineText = scriptDocument:GetLine(positionLine)
print(`Texto de la línea seleccionada: {lineText}`)
end)
else
print("No hay scripts abiertos")
end
GetLineCount
Devuelve
Muestras de código
--!nocheck
-- Ejecuta el siguiente código en la barra de comandos mientras un script está abierto
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(`¡El script tiene {lineCount} líneas!`)
else
print("No hay scripts abiertos")
end
GetScript
Devuelve
Muestras de código
--!nocheck
-- Ejecute el siguiente código en la Barra de Comandos mientras un script esté abierto
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(`Script actualmente abierto: {openScript:GetFullName()}`)
else
print("No hay scripts abiertos")
end
GetSelectedText
Devuelve
Muestras de código
--!nocheck
-- Ejecuta el siguiente código en la Barra de Comandos mientras un script esté abierto
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(`Texto actualmente seleccionado: {selectedText}`)
else
print("No hay texto actualmente seleccionado")
end
end)
else
print("No hay scripts abiertos")
end
GetSelectionEnd
Devuelve
Muestras de código
--!nocheck
-- Ejecuta el siguiente código en la Barra de Comandos mientras un script está abierto
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(`Inicio de selección: Línea {startLine}, Carácter {startCharacter}`)
print(`Fin de selección: Línea {endLine}, Carácter {endCharacter}`)
else
print("No hay scripts abiertos")
end
GetSelectionStart
Devuelve
Muestras de código
--!nocheck
-- Ejecuta el siguiente código en la Barra de Comandos mientras un script está abierto
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(`Inicio de selección: Línea {startLine}, Carácter {startCharacter}`)
print(`Fin de selección: Línea {endLine}, Carácter {endCharacter}`)
else
print("No hay scripts abiertos")
end
GetText
Parámetros
Devuelve
Muestras de código
--!nocheck
-- Ejecuta el siguiente código en la barra de comandos mientras un script esté abierto
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(`Contenido del script: {text}`)
else
print("No hay scripts abiertos")
end
GetViewport
Devuelve
Muestras de código
--!nocheck
-- Ejecuta el siguiente código en la Barra de Comandos mientras un script está abierto
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(`Actualmente viendo las líneas {firstLine} a {lastLine}`)
else
print("No hay scripts abiertos")
end
HasSelectedText
Devuelve
Muestras de código
--!nocheck
-- Ejecuta el siguiente código en la Barra de Comandos mientras un script esté abierto
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(`Texto actualmente seleccionado: {selectedText}`)
else
print("No hay texto actualmente seleccionado")
end
end)
else
print("No hay scripts abiertos")
end
IsCommandBar
Devuelve
Muestras de código
--!nocheck
-- Ejecuta el siguiente código en la Barra de Comandos
local ScriptEditorService = game:GetService("ScriptEditorService")
local documents = ScriptEditorService:GetScriptDocuments()
for _, document in documents do
if document:IsCommandBar() then
print("Documento de la barra de comandos:", document)
end
end
RequestSetSelectionAsync
Parámetros
Devuelve
Muestras de código
--!nocheck
-- Ejecuta el siguiente código en la barra de comandos mientras un script está abierto
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
-- Obtén el texto en la línea actual del cursor
local cursorLine = scriptDocument:GetSelection()
local lineText = scriptDocument:GetLine(cursorLine)
-- Forzar la selección de toda la línea de texto
local success, err = scriptDocument:RequestSetSelectionAsync(cursorLine, 1, cursorLine, #lineText + 1)
if success then
print("¡Selección establecida!")
else
print(`No se pudo establecer la selección debido a: {err}`)
end
else
print("No hay scripts abiertos")
end
Eventos
SelectionChanged
Parámetros
Muestras de código
--!nocheck
-- Ejecuta el siguiente código en la Barra de Comandos mientras un script está abierto
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(`Seleccionado: Línea {positionLine}, Carácter {positionCharacter}`)
print(`Ancla: Línea {anchorLine}, Carácter {anchorCharacter}`)
local lineText = scriptDocument:GetLine(positionLine)
print(`Texto de la línea seleccionada: {lineText}`)
end)
else
print("No hay scripts abiertos")
end
ViewportChanged
Parámetros
Muestras de código
--!nocheck
--[[
Para ejecutar:
1. Asegúrate de que la vista de Salida esté abierta
2. Ejecuta el siguiente código en la Barra de Comandos
3. Desplázate hacia arriba y hacia abajo en la ventana del Script abierta
Las declaraciones de impresión del evento ViewportChanged aparecerán en la Salida
]]
local Workspace = game:GetService("Workspace")
local ScriptEditorService = game:GetService("ScriptEditorService")
-- Crear texto que abarca muchas líneas
local dummyText = string.rep("-- Dummy Text\n", 60)
-- Crear un script que contenga el texto ficticio y abrirlo
local otherScript = Instance.new("Script")
otherScript.Source = dummyText
otherScript.Parent = Workspace
local success, err = ScriptEditorService:OpenScriptDocumentAsync(otherScript)
if not success then
warn(`Error al abrir el script porque: {err}`)
return
end
-- Obtener una referencia al script abierto
local scriptDocument = ScriptEditorService:FindScriptDocument(otherScript)
local function onViewportChanged(startLine: number, endLine: number)
print(`Viewport del Script Cambiado - startLine: {startLine}, endLine: {endLine}`)
end
-- Conectar el evento ViewportChanged a la función anterior que imprime la línea de inicio y la línea final del viewport actualizado
scriptDocument.ViewportChanged:Connect(onViewportChanged)