log in
substrata logo

User Interface Scripting in Luau

Luau scripts can show UI widgets, such as buttons, sliders, labels and windows, on the user's screen, over the 3D view.

When UI widgets can be created

So that scripts can't pop up widgets on the screen of everyone who comes near, a script can only create UI widgets after the user has interacted with it. A script is activated for the user when the user:

Events on other objects listened to with addEventListener also activate the script, if the other object was created by the same user as the script's object.

Once activated, the script stays activated, including when the script is reloaded. Scripts in their creator's personal world are always activated.

Calling a createUI function before the script is activated raises an error. So create your UI widgets in an event handler, for example:

--lua

local button = nil

function onUserUsedObject(av : Avatar, ob : Object)
	if button then
		button.visible = true
	else
		button = createUIButton({ text = "Close me", anchor = "bottom", offset = Vec2(0, 100),
			onClick = function() button.visible = false end })
	end
end

The error can be caught with pcall, if you want to handle it yourself.

Blocking

Users can right-click a widget (or long-press it on a touch screen) and choose "Block on-screen items from this object", or block widgets from all objects created by the same user. For a blocked script, the createUI functions don't raise an error, but return handles that do nothing, so the script keeps running as normal.

Users can see and unblock the widgets they have blocked with the blocked on-screen items button on the right edge of the screen. If you have blocked widgets from your own object, the script editor window shows a notice, with a link to unblock them.

Client and server

UI widgets only exist on the client. On the server the createUI functions return handles that do nothing, so a script that runs on both doesn't need to check IS_CLIENT around its UI code.

Callback functions such as onClick and onChange run only on the client of the user who clicked or changed the widget, not on the server.

Layout

Each createUI function takes a single table of parameters. Most widgets take these parameters:

anchor : stringThe point of the screen the widget is placed relative to. One of "top-left", "top", "top-right", "left", "centre", "right", "bottom-left", "bottom", "bottom-right". Default "centre".
offset : Vec2Offset of the widget from the anchor point, in pixels. +x is right, +y is up. Default Vec2(0, 0).
visible : booleanDefault true.
tooltip : stringText shown when the mouse is held over the widget. At most 200 bytes, on a single line (newlines are shown as spaces). The tooltip also always has a second line saying which object and user the widget is from. Default "" (only that line).

To lay out several widgets together, put them in a grid with grid:setCell(), and optionally put the grid in a window with window:setBody(). A widget in a grid or window is positioned by the grid or window, and its own anchor and offset are not used. Grids can be nested. Windows can't be put in grids or windows.

Positions and sizes are Vec2 values, e.g. Vec2(20, -20). A table with x and y fields, like {x=20, y=-20}, also works.

Unknown parameter names are reported as warnings in the log, so you can find misspelt parameters.

A script can create up to 1000 widgets.

Functions

The examples below create their widgets when the user uses the object, so using the object again creates the widgets again. To create widgets only once, keep the handle in a variable, as in the example at the top of the page.

createUIImage(params : table) : UIWidget
image_url : stringThe image to show. Must be declared in the script's comment header, see Declaring resources.
size : Vec2Size in pixels. Default Vec2(128, 128).
Creates an image. The image is shown once it has downloaded and loaded.

For example, to show an image in the top-right corner of the screen:

--lua
-- @resource logo.png

function onUserUsedObject(av : Avatar, ob : Object)
	createUIImage({ image_url = "logo.png", size = Vec2(64, 64), anchor = "top-right", offset = Vec2(-20, -20) })
end
createUIButton(params : table) : UIWidget
text : stringText shown on the button. Either text or image_url must be given, but not both.
image_url : stringImage shown on the button. Must be declared in the script's comment header.
size : Vec2Size in pixels, for image buttons. Default Vec2(32, 32).
onClick : functionCalled with no arguments when the button is clicked. Optional.
Creates a button with text or an image.

For example:

--lua

function onUserUsedObject(av : Avatar, ob : Object)
	createUIButton({ text = "Say hello", anchor = "bottom", offset = Vec2(0, 100), tooltip = "Shows a greeting",
		onClick = function() showMessage("Hello!") end })
end
createUILabel(params : table) : UIWidget
text : stringThe text. Can contain newlines.
text_colour : Vec3fNon-linear sRGB colour, components between 0 and 1. Default Vec3f(1, 1, 1).
font_size : numberIn pixels, between 6 and 100. Default is the default UI font size.
background_colour : Vec3fNon-linear sRGB colour. Default Vec3f(0, 0, 0).
background_alpha : numberBetween 0 and 1. Default 0 (no background).
size : Vec2Minimum size in pixels. The label is made bigger if needed to fit the text. An empty label with a size and a background is a plain rectangle of exactly that size. Default Vec2(0, 0): fit the text.
Creates a text label.

For example, to show some text on a semi-transparent background at the top of the screen:

--lua

function onUserUsedObject(av : Avatar, ob : Object)
	createUILabel({ text = "Welcome to my house!\nUse the door to open it.", font_size = 20,
		background_alpha = 0.5, anchor = "top", offset = Vec2(0, -50) })
end
createUISlider(params : table) : UIWidget
min : numberDefault 0.
max : numberDefault 1.
value : numberInitial value, clamped to between min and max. Default min.
onChange : functionCalled with the new value when the user changes the value. Optional.
width : numberWidth in pixels. Default 200.
Creates a horizontal slider.

For example, a slider with a label above it showing the value:

--lua

function onUserUsedObject(av : Avatar, ob : Object)
	local label = createUILabel({ text = "Brightness: 0.50", anchor = "bottom", offset = Vec2(0, 140) })
	createUISlider({ min = 0, max = 1, value = 0.5, anchor = "bottom", offset = Vec2(0, 100),
		onChange = function(value) label.text = string.format("Brightness: %.2f", value) end })
end
createUISpinBox(params : table) : UIWidget
min : numberDefault 0.
max : numberDefault 100.
value : numberInitial value, clamped to between min and max. Default min.
step : numberAmount the arrow buttons change the value by. Default 1.
decimals : numberNumber of decimal places shown, between 0 and 10. Default 3.
onChange : functionCalled with the new value when the user changes the value. Optional.
width : numberWidth in pixels. Default 100.
Creates a number box with up and down arrow buttons.

For example, a whole-number spin box:

--lua

function onUserUsedObject(av : Avatar, ob : Object)
	createUISpinBox({ min = 1, max = 10, value = 3, step = 1, decimals = 0,
		onChange = function(value) showMessage("Number of balls: " .. value) end })
end
createUICheckBox(params : table) : UIWidget
checked : booleanInitial state. Default false.
onChange : functionCalled with the new state (a boolean) when the user toggles the checkbox. Optional.
Creates a checkbox.

For example, a checkbox with a label next to it:

--lua

function onUserUsedObject(av : Avatar, ob : Object)
	createUILabel({ text = "Music", anchor = "bottom", offset = Vec2(-30, 100) })
	createUICheckBox({ checked = true, anchor = "bottom", offset = Vec2(20, 100),
		onChange = function(checked) showMessage(checked and "Music on" or "Music off") end })
end
createUIDropDown(params : table) : UIWidget
options : tableList of strings, e.g. {"Low", "Medium", "High"}. Between 1 and 100 options, each at most 200 bytes.
value : stringInitially selected option. Default is the first option.
onChange : functionCalled with the newly selected option (a string) when the user changes the selection. Optional.
width : numberWidth in pixels. Default 150.
Creates a drop-down list.

For example:

--lua

function onUserUsedObject(av : Avatar, ob : Object)
	createUIDropDown({ options = {"Red", "Green", "Blue"}, value = "Green",
		onChange = function(value) showMessage("You chose " .. value) end })
end
createUILineEdit(params : table) : UIWidget
text : stringInitial text. Default "".
onChange : functionCalled with the new text when the user changes the text. Optional.
onEnter : functionCalled with the text when the user presses enter. Optional.
width : numberWidth in pixels. Default 200.
Creates a single-line text box.

For example, a text box that greets the user when they press enter:

--lua

function onUserUsedObject(av : Avatar, ob : Object)
	createUILineEdit({ width = 200,
		onEnter = function(text) showMessage("Hello, " .. text) end })
end
createUIGrid(params : table) : UIWidget
background_colour : Vec3fNon-linear sRGB colour. Default Vec3f(0.1, 0.1, 0.1).
background_alpha : numberBetween 0 and 1. Default 0 (no background). If greater than 0, clicks on the background don't go through to the world.
interior_padding : numberPadding in pixels on each cell side that faces another cell, so the gap between adjacent cells is twice this. Default 5.
edge_padding : numberPadding in pixels on each cell side that faces the edge of the grid. Default 10.
Creates a grid, for laying out other widgets in rows and columns. Add widgets with grid:setCell() or grid:addRow(). A grid has at most 32 rows and 32 columns.

For example, a label and a text box side by side, with an OK button underneath that hides the grid:

--lua

function onUserUsedObject(av : Avatar, ob : Object)
	local grid = createUIGrid({ background_alpha = 0.7, anchor = "left", offset = Vec2(20, 0) })
	local name_edit = createUILineEdit({ width = 150 })
	grid:setCell(1, 1, createUILabel({ text = "Name:" }))
	grid:setCell(2, 1, name_edit)
	grid:addRow(createUIButton({ text = "OK",
		onClick = function()
			showMessage("Hello, " .. name_edit.text)
			grid.visible = false
		end }))
end
createUIWindow(params : table) : UIWidget
title : stringDefault "".
background_colour : Vec3fNon-linear sRGB colour. Default Vec3f(0.1, 0.1, 0.1).
background_alpha : numberBetween 0 and 1. Default 0.9.
padding : numberPadding around the window contents, in pixels, between 0 and 100. Default 10.
onClose : functionCalled with no arguments after the user clicks the close button. Optional.
Creates a window with a title bar and a close button. Set its contents with window:setBody(), usually with a grid. The close button hides the window. Show it again by setting window.visible = true.

For example, a window containing a label:

--lua

function onUserUsedObject(av : Avatar, ob : Object)
	local window = createUIWindow({ title = "Info", anchor = "top-left", offset = Vec2(20, -20),
		onClose = function() showMessage("Window closed") end })
	window:setBody(createUILabel({ text = "Close this window with the close button." }))
end

UIWidget

The handle returned by the createUI functions.

Attributes:

visible : booleanIs the widget shown? A widget in a grid or window is only shown if the grid or window is shown too.
offset : Vec2Offset of the widget from its anchor point, in pixels. Has no visible effect while the widget is in a grid or window.
text : stringThe text of a text button, label or line edit. Can only be read for line edits.
value : number or stringThe value of a slider or spin box (a number), or the selected option of a drop-down list (a string).
checked : booleanThe state of a checkbox.
tooltip : stringThe widget's tooltip text, see the tooltip parameter above.

Setting text, value or checked from the script doesn't call the widget's onChange function.

Methods:

destroy()Removes the widget. Destroying a grid or window also destroys the widgets in it. Widgets are also removed when the script is reloaded or its object is removed.
setCell(column : number, row : number, widget : UIWidget)For grids. Puts the widget in the cell. Column and row start at 1, and (1, 1) is the top-left cell. If widget is nil, clears the cell. A widget removed from a grid goes back to being positioned by its own anchor and offset.
addRow(widget : UIWidget)For grids. Puts the widget in the first column of a new row at the bottom of the grid.
setBody(widget : UIWidget)For windows. Makes the widget the contents of the window. If widget is nil, removes the current contents.

Example

This script shows a settings window with one of each kind of widget when the user uses the object.

--lua
-- @resource 67e_jpg_12057920870970093540.jpg
-- @resource microphone_png_2695896580343548136.png

local window = nil -- Created the first time the user uses the object.

local function createSettingsWindow()
	window = createUIWindow({ title = "Settings", anchor = "top-left", offset = Vec2(20, -20),
		onClose = function() print("Window closed") end })

	local grid = createUIGrid({ interior_padding = 5, edge_padding = 0 })
	window:setBody(grid)

	local title = createUILabel({ text = "Options", text_colour = Vec3f(1, 0.9, 0.2), font_size = 18 })
	local cat = createUIImage({ image_url = "67e_jpg_12057920870970093540.jpg", size = Vec2(64, 64) })
	grid:setCell(1, 1, title)
	grid:setCell(2, 1, cat)

	local volume_label = createUILabel({ text = "Volume: 0.5" })
	local volume_slider = createUISlider({ min = 0, max = 1, value = 0.5, width = 150,
		onChange = function(value) volume_label.text = string.format("Volume: %.2f", value) end })
	grid:setCell(1, 2, volume_label)
	grid:setCell(2, 2, volume_slider)

	local lights_label = createUILabel({ text = "Lights on" })
	local lights_checkbox = createUICheckBox({ checked = true,
		onChange = function(checked) lights_label.text = checked and "Lights on" or "Lights off" end })
	grid:setCell(1, 3, lights_label)
	grid:setCell(2, 3, lights_checkbox)

	local quality_label = createUILabel({ text = "Quality: Medium" })
	local quality_dropdown = createUIDropDown({ options = {"Low", "Medium", "High"}, value = "Medium", width = 120,
		onChange = function(value) quality_label.text = "Quality: " .. value end })
	grid:setCell(1, 4, quality_label)
	grid:setCell(2, 4, quality_dropdown)

	local name_label = createUILabel({ text = "Name:" })
	local name_edit = createUILineEdit({ text = "", width = 150,
		onEnter = function(text) showMessage("Hello, " .. text) end })
	grid:setCell(1, 5, name_label)
	grid:setCell(2, 5, name_edit)

	local count_label = createUILabel({ text = "Count:" })
	local count_spinbox = createUISpinBox({ min = 1, max = 10, value = 3, step = 1, decimals = 0, width = 80,
		onChange = function(value) print("Count is now " .. value) end })
	grid:setCell(1, 6, count_label)
	grid:setCell(2, 6, count_spinbox)

	local reset_button = createUIButton({ text = "Reset",
		onClick = function()
			volume_slider.value = 0.5 -- Setting value or checked doesn't call onChange, so update the labels as well.
			volume_label.text = "Volume: 0.50"
			lights_checkbox.checked = true
			lights_label.text = "Lights on"
			quality_dropdown.value = "Medium"
			quality_label.text = "Quality: Medium"
			name_edit.text = ""
			count_spinbox.value = 3
		end })
	grid:addRow(reset_button) -- Puts the button in column 1 of a new row at the bottom.

	local mic_button = createUIButton({ image_url = "microphone_png_2695896580343548136.png", size = Vec2(24, 24),
		onClick = function() cat.visible = not cat.visible end })
	grid:setCell(2, 7, mic_button) -- Next to the reset button.
end

function onUserUsedObject(av : Avatar, ob : Object)
	if window then
		window.visible = true -- Show the window again if it was closed.
	else
		createSettingsWindow()
	end
end


< Luau scripting