### Example of 'post' Render Type in Lua
Source: https://basalt.madefor.cc/guides/canvas.html
Provides an example of creating a canvas with the 'post' render type and adding commands that execute after the main object rendering, such as drawing overlay text.
```lua
-- Create a canvas that renders after the main object
local canvas = main:addCanvas()
canvas:setType("post")
-- Add commands that will now execute after main rendering
canvas:addCommand(function()
canvas:drawText(1, 1, "Overlay Text")
end)
-- or
canvas:line(1, 1, 10, 10, " ", colors.red, colors.green)
```
--------------------------------
### Install Basalt with Custom Filename/Directory (Lua)
Source: https://basalt.madefor.cc/guides/download.html
These examples show how to specify a custom output filename for Release versions (Core, Full) or a custom directory name for the Dev version when installing Basalt. This allows for better organization of downloaded files.
```lua
-- Install Core version as "myapp.lua"
wget run https://raw.githubusercontent.com/Pyroxenium/Basalt2/main/install.lua -r myapp.lua
-- Install Full version with default name
wget run https://raw.githubusercontent.com/Pyroxenium/Basalt2/main/install.lua -f
-- Install Dev version in "basalt-dev" folder
wget run https://raw.githubusercontent.com/Pyroxenium/Basalt2/main/install.lua -d basalt-dev
```
--------------------------------
### Render Basalt UI to a Monitor (Lua)
Source: https://basalt.madefor.cc/guides/getting-started.html
This code shows how to use Basalt to render a UI on a computer monitor peripheral. It involves finding the monitor, creating a specific frame for it, adding elements to that frame, and then calling `basalt.run()` to start the event loop for all managed frames.
```lua
local basalt = require("basalt")
local main = basalt.getMainFrame()
-- Get a reference to the monitor
local monitor = peripheral.find("monitor")
-- Or use a specific side: peripheral.wrap("right")
-- Create a frame for the monitor
local monitorFrame = basalt.createFrame()
:setTerm(monitor)
-- Add elements like normal
monitorFrame:addButton()
:setText("Monitor Button")
:setSize(24, 3)
:setPosition(2, 2)
-- Start Basalt (handles all frames automatically)
basalt.run()
```
--------------------------------
### Create a Basic Window with a Button in Basalt (Lua)
Source: https://basalt.madefor.cc/guides/getting-started.html
This snippet demonstrates how to create a main window and add a clickable button to it using the Basalt library. The button's text changes when clicked. It requires the Basalt library to be available.
```lua
local basalt = require("basalt")
-- Get the main frame (your window)
local main = basalt.getMainFrame()
-- Add a button
main:addButton()
:setText("Click me!")
:setPosition(4, 4)
:onClick(function(self)
self:setText("Clicked!")
end)
-- Start Basalt (starts the event loop)
basalt.run()
```
--------------------------------
### Add Various UI Elements in Basalt (Lua)
Source: https://basalt.madefor.cc/guides/getting-started.html
This code example shows how to add different UI elements such as labels, input fields, and lists to a Basalt frame. Each element is positioned and configured using method chaining. This assumes a Basalt frame has already been initialized.
```lua
-- Add a label (text)
main:addLabel()
:setText("Hello World")
:setPosition(4, 2)
-- Add an input field
main:addInput()
:setPosition(4, 6)
:setSize(20, 1)
-- Add a list
main:addList()
:setPosition(4, 8)
:setSize(20, 6)
:addItem("Item 1")
:addItem("Item 2")
```
--------------------------------
### Basalt Command-Line Options (Bash)
Source: https://basalt.madefor.cc/guides/download.html
This snippet demonstrates various command-line options for the Basalt installer script using `wget run`. It includes showing help, installing specific versions (Core, Full, Dev), and specifying an output path or directory.
```bash
# Show help
wget run https://raw.githubusercontent.com/Pyroxenium/Basalt2/main/install.lua -h
# Install Core version (default, recommended)
wget run https://raw.githubusercontent.com/Pyroxenium/Basalt2/main/install.lua -r [path]
# Install Full version (all elements)
wget run https://raw.githubusercontent.com/Pyroxenium/Basalt2/main/install.lua -f [path]
# Install Dev version (source files)
wget run https://raw.githubusercontent.com/Pyroxenium/Basalt2/main/install.lua -d [path]
```
--------------------------------
### Tree Example (Executable)
Source: https://basalt.madefor.cc/references/elements/Tree.html
An executable Lua example demonstrating how to create and populate a Basalt Tree component.
```APIDOC
## Example (Executable)
▶Run
```lua
local basalt = require("basalt")
local main = basalt.getMainFrame()
local fileTree = main:addTree()
:setPosition(2, 2)
:setSize(15, 15)
:setBackground(colors.black)
:setForeground(colors.white)
:setSelectedBackgroundColor(colors.blue)
:setSelectedForegroundColor(colors.white)
:setScrollBarColor(colors.lightGray)
:setScrollBarBackgroundColor(colors.gray)
-- Build a file system-like tree structure
local treeData = {
{
text = "Root",
children = {
{
text = "Documents",
children = {
{text = "report.txt"},
{text = "notes.txt"},
{text = "todo.txt"}
}
},
{
text = "Pictures",
children = {
{text = "vacation.png"},
{text = "family.jpg"},
{
text = "Archive",
children = {
{text = "old_photo1.jpg"},
{text = "old_photo2.jpg"},
{text = "old_photo3.jpg"}
}
}
}
},
{
text = "Music",
children = {
{text = "song1.mp3"},
{text = "song2.mp3"},
{text = "song3.mp3"},
{text = "song4.mp3"}
}
},
{
text = "Videos",
children = {
{text = "movie1.mp4"},
{text = "movie2.mp4"}
}
},
{
text = "Projects",
children = {
{
text = "ProjectA",
children = {
{text = "src"},
{text = "tests"},
{text = "README.md"}
}
},
{
text = "ProjectB",
children = {
{text = "main.lua"},
{text = "config.lua"}
}
}
}
}
}
}
fileTree:setNodes(treeData)
local textLabel = main:addLabel()
:setPosition(2, 18)
:setForeground(colors.yellow)
:setText("Selected: None")
-- Handle node selection
fileTree:onSelect(function(self, node)
textLabel
:setText("Selected: " .. node.text)
:setPosition(2, 18)
:setForeground(colors.yellow)
end)
-- Info label
main:addLabel()
:setText("Click nodes to expand/collapse | Scroll to navigate")
:setPosition(2, 1)
:setForeground(colors.lightGray)
basalt.run()
```
```
--------------------------------
### Advanced Multi-Blit Example in Lua
Source: https://basalt.madefor.cc/guides/canvas.html
Shows an advanced usage of `multiBlit` for efficiently rendering text within a rectangular area. It takes position, dimensions, text, and color strings.
```lua
canvas:addCommand(function()
-- Parameters: x, y, width, height, text, fg, bg
canvas:multiBlit(1, 1, 5, 3,
"HelloWorld!Hello", -- text (width * height characters)
"ffffffffff", -- fg colors (width * height characters)
"0000000000" -- bg colors (width * height characters)
)
end)
```
--------------------------------
### Practical Basalt Benchmarking Example
Source: https://basalt.madefor.cc/guides/benchmarks.html
This practical example illustrates how to integrate Basalt's benchmarking tools into an application. It includes creating a button to trigger benchmark logging for 'render' performance, setting up test elements, and running the Basalt application. This demonstrates a real-world use case for performance analysis.
```lua
local basalt = require("basalt")
local main = basalt.getMainFrame()
-- Create a benchmark trigger button
main:addButton()
:setText("Show Benchmarks")
:setPosition(2, 2)
:onClick(function()
main:logContainerBenchmarks("render")
end)
-- Create some test elements
local program = main:addProgram()
:execute("shell.lua")
local complexFrame = main:addFrame()
:setPosition(30, 1)
:addButton()
:addLabel()
:addList()
-- Start benchmarking
main:benchmarkContainer("render")
basalt.run()
```
--------------------------------
### Start and Log Container Benchmarks in Basalt
Source: https://basalt.madefor.cc/guides/benchmarks.html
This snippet demonstrates the basic usage of Basalt's benchmarking tools. It shows how to start tracking the 'render' performance of a container and then log the collected benchmark results to the console. No external dependencies are required beyond the Basalt library.
```lua
local main = basalt.getMainFrame()
-- Start benchmarking a container
main:benchmarkContainer("render") -- Start tracking render performance
-- Log benchmark results
main:logContainerBenchmarks("render") -- Print results to console
```
--------------------------------
### Complete Element Loading Example in Lua
Source: https://basalt.madefor.cc/guides/element-loading.html
A comprehensive example demonstrating the configuration, registration of disk and remote sources, preloading, and usage of elements within the Basalt framework.
```lua
local basalt = require("basalt")
local elementManager = basalt.getElementManager()
-- Configure loading system
elementManager.configure({
autoLoadMissing = true,
allowRemoteLoading = true,
allowDiskLoading = true,
useGlobalCache = true
})
-- Register disk mount for custom elements
if fs.exists("/disk") then
elementManager.registerDiskMount("/disk")
end
-- Register remote element
elementManager.registerRemoteSource(
"SpecialButton",
"https://raw.githubusercontent.com/user/repo/main/SpecialButton.lua"
)
-- Preload common elements
elementManager.preloadElements({"Button", "Label", "Frame"})
-- Use elements normally
local main = basalt.getMainFrame()
local btn = main:addButton()
:setText("Standard Button")
:setPosition(2, 2)
-- This will be loaded from disk or remote if available
local special = main:addSpecialButton()
:setText("Special Button")
:setPosition(2, 4)
basalt.run()
```
--------------------------------
### Install Element - Basalt API
Source: https://basalt.madefor.cc/references/main.html
The `basalt.install` function installs a specified element. You provide the element name, and optionally a source URL or path for the installation. This allows for interactive installation or installation from a specific location.
```lua
basalt.install("Slider")
```
```lua
basalt.install("Slider", "https://example.com/slider.lua")
```
--------------------------------
### Adaptive Layout Example in Lua
Source: https://basalt.madefor.cc/guides/responsive-system.html
A practical example of creating an adaptive layout using Basalt. This script demonstrates how to arrange UI elements side-by-side on wide screens and stack them vertically on narrow screens, with a status label updating to reflect the current layout mode. Requires the 'basalt' library.
```lua
local basalt = require("basalt")
local main = basalt.getMainFrame()
-- Left container
local rightContainer = main:addFrame()
:setSize(20, 10)
:setBackground(colors.green)
:responsive()
:when("parent.width >= 45") -- Wide: positioned next to left
:apply({
x = 24,
y = 2,
width = 20
})
:otherwise({
x = 2,
y = 13,
width = "{parent.width - 3}"
}) -- Narrow: positioned below left
:done()
rightContainer:addLabel()
:setText("Right Panel")
:setPosition(2, 2)
-- Status label showing current layout mode
local statusLabel = main:addLabel()
:setPosition(2, 24)
:responsive()
:when("parent.width >= 45")
:apply({ text = "Layout: Side by Side", foreground = colors.lime })
:otherwise({ text = "Layout: Stacked", foreground = colors.orange })
:done()
basalt.run()
```
--------------------------------
### Element Installation API
Source: https://basalt.madefor.cc/references/main.html
API for installing an element, either interactively or from a specified source.
```APIDOC
## POST /basalt/install
### Description
Installs an element interactively or from a specified source.
### Method
POST
### Endpoint
/basalt/install
### Parameters
#### Request Body
- **elementName** (string) - Required - The name of the element to install.
- **source** (string) - Optional - Optional source URL or path.
### Request Example
```json
{
"elementName": "Slider"
}
```
```json
{
"elementName": "Slider",
"source": "https://example.com/slider.lua"
}
```
```
--------------------------------
### Start Animation Instance
Source: https://basalt.madefor.cc/references/plugins/animation.html
Starts a previously created AnimationInstance. This method returns the instance itself, allowing for chaining.
```lua
animInstance:start()
```
--------------------------------
### Install Basalt UI Framework
Source: https://basalt.madefor.cc/guides/faq.html
Installs the Basalt UI framework using a provided Lua script. This is the primary method for setting up Basalt on CC:Tweaked.
```shell
wget run https://raw.githubusercontent.com/Pyroxenium/Basalt2/main/install.lua
```
--------------------------------
### Load Basalt After Installation (Lua)
Source: https://basalt.madefor.cc/guides/download.html
This code snippet demonstrates how to load the Basalt library into your Lua program after it has been successfully installed. It uses the `require` function to make Basalt's functionalities available.
```lua
local basalt = require("basalt")
```
--------------------------------
### Basalt Example with Logging
Source: https://basalt.madefor.cc/guides/debugging.html
A comprehensive example of using the Basalt logging system within an application. It shows how to enable logging, create UI elements, and log events like button clicks and data processing outcomes.
```lua
local basalt = require("basalt")
basalt.LOGGER.setEnabled(true)
basalt.LOGGER.setLogToFile(true)
local main = basalt.getMainFrame()
local button = main:addButton()
:setText("Click Me")
:setPosition(2, 2)
:onClick(function(self)
basalt.LOGGER.debug("Button clicked")
local data = loadData()
basalt.LOGGER.info("Loaded " .. #data .. " items")
local success = processData(data)
if not success then
basalt.LOGGER.error("Failed to process data")
end
end)
basalt.run()
```
--------------------------------
### Create and Configure a SideNav in Lua
Source: https://basalt.madefor.cc/references/elements/SideNav.html
This Lua code demonstrates how to create a SideNav component using the Basalt library. It includes setting up multiple tabs, adding labels and buttons to each tab, and handling button clicks to update UI elements. This example requires the Basalt library to be installed and available.
```lua
local basalt = require("basalt")
local main = basalt.getMainFrame()
-- Create a simple SideNav
local sideNav = main:addSideNav({
x = 1,
y = 1,
sidebarWidth = 12,
width = 48
})
-- Tab 1: Home
local homeTab = sideNav:newTab("Home")
homeTab:addLabel({
x = 2,
y = 2,
text = "Welcome!",
foreground = colors.yellow
})
homeTab:addLabel({
x = 2,
y = 4,
text = "This is a simple",
foreground = colors.white
})
homeTab:addLabel({
x = 2,
y = 5,
text = "SideNav example.",
foreground = colors.white
})
-- Tab 2: Counter
local counterTab = sideNav:newTab("Counter")
local counterLabel = counterTab:addLabel({
x = 2,
y = 2,
text = "Count: 0",
foreground = colors.lime
})
local count = 0
counterTab:addButton({
x = 2,
y = 4,
width = 12,
height = 3,
text = "Click Me",
background = colors.blue
})
:setBackgroundState("clicked", colors.lightBlue)
:onClick(function()
count = count + 1
counterLabel:setText("Count: " .. count)
end)
-- Tab 3: Info
local infoTab = sideNav:newTab("Info")
infoTab:addLabel({
x = 2,
y = 2,
text = "SideNav Features:",
foreground = colors.orange
})
infoTab:addLabel({
x = 2,
y = 4,
text = "- Multiple tabs",
foreground = colors.gray
})
infoTab:addLabel({
x = 2,
y = 5,
text = "- Easy navigation",
foreground = colors.gray
})
infoTab:addLabel({
x = 2,
y = 6,
text = "- Content per tab",
foreground = colors.gray
})
basalt.run()
```
--------------------------------
### Handle Basic User Events for Elements in Basalt (Lua)
Source: https://basalt.madefor.cc/guides/getting-started.html
This example demonstrates how to attach event handlers to Basalt UI elements for common user interactions like clicks and mouse entry, as well as property changes. The 'self' parameter in the callbacks refers to the element itself, and 'value' provides the new data for change events.
```lua
element:onClick(function(self)
-- Called when clicked
-- 'self' refers to the element that was clicked
end)
element:onEnter(function(self)
-- Called when mouse enters (CraftOS-PC only)
end)
element:onChange("text", function(self, value)
-- Called when the "text" property changes
-- 'value' contains the new value
end)
```
--------------------------------
### Install Basalt Core Version (Lua)
Source: https://basalt.madefor.cc/guides/download.html
Downloads and installs the Core version of Basalt, which includes essential elements. This is recommended for smaller projects and environments with limited storage. The `-r` flag specifies the Core version.
```lua
wget run https://raw.githubusercontent.com/Pyroxenium/Basalt2/main/install.lua -r
```
--------------------------------
### Start and End Method Profiling with BaseElement
Source: https://basalt.madefor.cc/references/plugins/benchmark.html
These methods are used to start and end the timing of a specific method call within a BaseElement. They help in identifying performance bottlenecks by measuring execution time. No external dependencies are required beyond the BaseElement instance.
```lua
element:startProfile("methodName")
-- ... code to profile ...
element:endProfile("methodName")
```
--------------------------------
### Install Basalt Full Version (Lua)
Source: https://basalt.madefor.cc/guides/download.html
Downloads and installs the Full version of Basalt, which includes all elements and plugins. Use this version for large projects requiring advanced features and maximum flexibility. The `-f` flag specifies the Full version.
```lua
wget run https://raw.githubusercontent.com/Pyroxenium/Basalt2/main/install.lua -f
```
--------------------------------
### Basalt Initialization and Core Functions
Source: https://basalt.madefor.cc/references/main.html
This section covers the basic setup and core functions of the Basalt framework, including how to load it, create UI elements, and manage frames.
```APIDOC
## Basalt Initialization
### Description
Loads the Basalt library into your project. You can then access its functionalities through the `basalt` variable.
### Usage
```lua
local basalt = require("basalt")
```
## basalt.create(type, properties?)
### Description
Creates and returns a new UI element of the specified type.
### Parameters
* `type` `string` - The type of element to create (e.g. "Button", "Label", "BaseFrame")
* `properties` (optional) `string|table` - Optional name for the element or a table with properties to initialize the element with
### Returns
* `table` `element` - The created element instance
### Usage
```lua
local button = basalt.create("Button")
```
## basalt.createFrame()
### Description
Creates and returns a new BaseFrame.
### Returns
* `BaseFrame` `BaseFrame` - The created frame instance
## basalt.getElementManager()
### Description
Returns the element manager instance.
### Returns
* `table` `ElementManager` - The element manager
## basalt.getErrorManager()
### Description
Returns the error manager instance.
### Returns
* `table` `ErrorManager` - The error manager
## basalt.getMainFrame()
### Description
Gets or creates the main frame.
### Returns
* `BaseFrame` `BaseFrame` - The main frame instance
## basalt.setActiveFrame(frame, setActive?)
### Description
Sets the active frame.
### Parameters
* `frame` `BaseFrame` - The frame to set as active
* `setActive` (optional) `boolean` - Whether to set the frame as active (default: true)
## basalt.getActiveFrame(t?)
### Description
Returns the active frame.
### Parameters
* `t` (optional) `term` - The term to get the active frame for (default: current term)
### Returns
* `BaseFrame` `The` frame to set as active
## basalt.setFocus(frame)
### Description
Sets a frame as focused.
### Parameters
* `frame` `BaseFrame` - The frame to set as focused
## basalt.getFocus()
### Description
Returns the focused frame.
### Returns
* `BaseFrame` `The` focused frame
```
--------------------------------
### Start Animation
Source: https://basalt.madefor.cc/references/plugins/animation.html
Starts the execution of an Animation object or sequence. Returns the animation instance for chaining.
```lua
anim:start()
```
--------------------------------
### Install Basalt Dev Version (Lua)
Source: https://basalt.madefor.cc/guides/download.html
Downloads and installs the Dev version of Basalt, providing the complete source code as individual files. This is ideal for development, debugging, contributing to the project, or learning its internal workings. The `-d` flag specifies the Dev version.
```lua
wget run https://raw.githubusercontent.com/Pyroxenium/Basalt2/main/install.lua -d
```
--------------------------------
### TextBox:getText
Source: https://basalt.madefor.cc/references/elements/TextBox.html
Gets the text of the TextBox.
```APIDOC
## TextBox:getText()
### Description
Gets the text of the TextBox
### Method
N/A
### Endpoint
N/A
### Parameters
N/A
### Request Example
N/A
### Response
- **string** (text) - The text of the TextBox
### Response Example
N/A
```
--------------------------------
### Program Class Overview
Source: https://basalt.madefor.cc/references/elements/Program.html
This section provides an overview of the Program class, its inheritance, and executable examples.
```APIDOC
## Program Class
_This is the program class. It provides a program that runs in a window._
Extends: `VisualElement`
### Examples (Executable)
▶Run
lua
```lua
local basalt = require("basalt")
local main = basalt.getMainFrame()
local execPath = "rom/programs/fun/worm.lua"
local btn = main:addButton({
x = 5,
y = 2,
width = 20,
height = 3,
text = "Run Worm",
}):onClick(function()
local frame = main:addFrame({
x = 2,
y = 2,
width = 28,
height = 10,
title = "Worm Program",
draggable = true,
})
:setDraggingMap({{x=1, y=1, width=27, height=1}})
:onFocus(function(self)
self:prioritize()
end)
local program = frame:addProgram({
x = 1,
y = 2,
width = 28,
height = 9,
})
program:execute(execPath)
frame:addLabel({
x = 2,
y = 1,
text = "Worm",
foreground = colors.lightBlue
})
frame:addButton({
x = frame.get("width"),
y = 1,
width = 1,
height = 1,
text = "X",
background = colors.red,
foreground = colors.white
}):onClick(function()
frame:destroy()
end)
end)
basalt.run()
```
```
--------------------------------
### Lua TabControl Example
Source: https://basalt.madefor.cc/references/elements/TabControl.html
This Lua code snippet demonstrates how to create and populate a TabControl in Basalt. It includes three tabs: 'Home' with welcome messages, 'Counter' with a clickable button to increment a counter, and 'Info' displaying features of the TabControl. The example utilizes various Basalt UI elements like labels and buttons within each tab.
```lua
local basalt = require("basalt")
local main = basalt.getMainFrame()
-- Create a simple TabControl
local tabControl = main:addTabControl({
x = 2,
y = 2,
width = 46,
height = 15,
})
-- Tab 1: Home
local homeTab = tabControl:newTab("Home")
homeTab:addLabel({
x = 2,
y = 2,
text = "Welcome!",
foreground = colors.yellow
})
homeTab:addLabel({
x = 2,
y = 4,
text = "This is a TabControl",
foreground = colors.white
})
homeTab:addLabel({
x = 2,
y = 5,
text = "example with tabs.",
foreground = colors.white
})
-- Tab 2: Counter
local counterTab = tabControl:newTab("Counter")
local counterLabel = counterTab:addLabel({
x = 2,
y = 2,
text = "Count: 0",
foreground = colors.lime
})
local count = 0
counterTab:addButton({
x = 2,
y = 4,
width = 12,
height = 3,
text = "Click Me",
background = colors.blue
})
:setBackgroundState("clicked", colors.lightBlue)
:onClick(function()
count = count + 1
counterLabel:setText("Count: " .. count)
end)
-- Tab 3: Info
local infoTab = tabControl:newTab("Info")
infoTab:addLabel({
x = 2,
y = 2,
text = "TabControl Features:",
foreground = colors.orange
})
infoTab:addLabel({
x = 2,
y = 4,
text = "- Horizontal tabs",
foreground = colors.gray
})
infoTab:addLabel({
x = 2,
y = 5,
text = "- Easy navigation",
foreground = colors.gray
})
infoTab:addLabel({
x = 2,
y = 6,
text = "- Content per tab",
foreground = colors.gray
})
basalt.run()
```
--------------------------------
### Advanced Custom Tag Example: Dialog in Basalt (Lua)
Source: https://basalt.madefor.cc/guides/xml.html
Provides an example of registering and using a complex custom XML tag, 'dialog', which creates a modal window with a title bar, close button, and content area.
```lua
XMLParser.registerTagHandler("dialog", function(node, parent, scope)
local dialog = parent:addFrame()
dialog:setSize(30, 15)
dialog:setBackground(colors.black)
dialog:addBorder({left=true, right=true, top=true, bottom=true})
dialog:center()
-- Title bar
if node.attributes.title then
local title = node.attributes.title:gsub("^\"", ""):gsub("\"$", "")
local titleBar = dialog:addLabel()
titleBar:setText(title)
titleBar:setPosition(2, 1)
titleBar:setForeground(colors.white)
end
-- Close button
local closeBtn = dialog:addButton()
closeBtn:setText("X")
closeBtn:setPosition(28, 1)
closeBtn:setSize(2, 1)
closeBtn:onClick(function()
dialog:remove()
end)
-- Content area (process children)
if node.children then
for _, child in ipairs(node.children) do
local childTag = child.tag:sub(1,1):upper() .. child.tag:sub(2)
if dialog["add" .. childTag] then
local element = dialog["add" .. childTag](dialog)
element:fromXML(child, scope)
end
end
end
return dialog
end)
-- Usage
main:loadXML([[
]])
```
--------------------------------
### Image:getImageSize()
Source: https://basalt.madefor.cc/references/elements/Image.html
Gets the size of the image.
```APIDOC
## Image:getImageSize()
### Description
Gets the size of the image.
### Returns
* `number` - `width` The width of the image.
* `number` - `height` The height of the image.
```
--------------------------------
### Get Plugin API by Name
Source: https://basalt.madefor.cc/references/elementManager.html
Retrieves a Plugin API by its specified name. Returns the API object as a table.
```lua
ElementManager.getAPI(name)
```
--------------------------------
### Get List of All Elements
Source: https://basalt.madefor.cc/references/elementManager.html
Retrieves a list of all currently registered and loaded elements. Returns a table containing the elements.
```lua
ElementManager.getElementList()
```
--------------------------------
### Create and Style BigFont Text in Basalt
Source: https://basalt.madefor.cc/references/elements/BigFont.html
Demonstrates how to create a BigFont element, set its position, font size, text content, and foreground color. It also includes an example of animating the text color.
```lua
-- Create a large welcome message
local main = basalt.getMainFrame()
local title = main:addBigFont()
:setPosition(3, 3)
:setFontSize(2) -- Makes text twice as large
:setText("Welcome!")
:setForeground(colors.yellow) -- Make text yellow
-- For animated text
basalt.schedule(function()
while true do
title:setForeground(colors.yellow)
sleep(0.5)
title:setForeground(colors.orange)
sleep(0.5)
end
end)
```
--------------------------------
### Configure Button States with Inline XML Attributes
Source: https://basalt.madefor.cc/guides/states.html
This example demonstrates configuring button states using inline attributes within the XML element. This provides a concise way to set state-specific properties.
```xml
```
--------------------------------
### ScrollFrame Example in Lua
Source: https://basalt.madefor.cc/references/elements/ScrollFrame.html
This Lua code demonstrates how to create and configure a ScrollFrame in Basalt. It adds a title, multiple labels that exceed the frame's height, and interactive buttons. The example also includes an informational label outside the scroll frame to guide the user on scrolling.
```lua
local basalt = require("basalt")
local main = basalt.getMainFrame()
-- Create a ScrollFrame with content larger than the frame
local scrollFrame = main:addScrollFrame({
x = 2,
y = 2,
width = 30,
height = 12,
background = colors.lightGray
})
-- Add a title
scrollFrame:addLabel({
x = 2,
y = 1,
text = "ScrollFrame Example",
foreground = colors.yellow
})
-- Add multiple labels that exceed the frame height
for i = 1, 20 do
scrollFrame:addLabel({
x = 2,
y = i + 2,
text = "Line " .. i .. " - Scroll to see more",
foreground = i % 2 == 0 and colors.white or colors.lightGray
})
end
-- Add some interactive buttons at different positions
scrollFrame:addButton({
x = 2,
y = 24,
width = 15,
height = 3,
text = "Button 1",
background = colors.blue
})
:onClick(function()
scrollFrame:addLabel({
x = 18,
y = 24,
text = "Clicked!",
foreground = colors.lime
})
end)
scrollFrame:addButton({
x = 2,
y = 28,
width = 15,
height = 3,
text = "Button 2",
background = colors.green
})
:onClick(function()
scrollFrame:addLabel({
x = 18,
y = 28,
text = "Nice!",
foreground = colors.orange
})
end)
-- Info label outside the scroll frame
main:addLabel({
x = 2,
y = 15,
text = "Use mouse wheel to scroll!",
foreground = colors.gray
})
basalt.run()
```
--------------------------------
### Initialize Canvas Object in Lua
Source: https://basalt.madefor.cc/guides/canvas.html
Demonstrates how to get the canvas object from a Basalt frame. This is the first step to using any canvas drawing functions.
```lua
local main = basalt.createFrame()
local canvas = main:getCanvas()
```
--------------------------------
### Draw Line on Canvas in Lua
Source: https://basalt.madefor.cc/guides/canvas.html
Shows how to draw a line on the canvas. It requires start and end coordinates, a character for the line, and foreground and background colors.
```lua
canvas:line(1, 1, 10, 10, "*", colors.red, colors.black) -- Draws a red line
```
--------------------------------
### Get Selected Items (Lua)
Source: https://basalt.madefor.cc/references/elements/Collection.html
Provides an example of how to retrieve all currently selected items from the Collection. The function returns a table containing the selected items. This is useful for batch operations on selected elements.
```lua
local selected = Collection:getSelectedItems()
```
--------------------------------
### Basalt Benchmark Methods for Containers
Source: https://basalt.madefor.cc/guides/benchmarks.html
This section lists and describes the available methods for benchmarking within Basalt containers. It covers how to start and log benchmarks for specific container methods like 'render', 'mouse_click', 'mouse_up', and 'mouse_drag'. These methods help in identifying performance bottlenecks in different interaction types.
```lua
-- Track specific container methods
container:benchmarkContainer(methodName) -- Start tracking
container:logContainerBenchmarks(methodName) -- Show results
-- Common methods to benchmark:
- "render" -- Track render performance
- "mouse_click" -- Track click handling
- "mouse_up" -- Track release handling
- "mouse_drag" -- Track drag performance
```
--------------------------------
### Add Custom Drawing Command in Lua
Source: https://basalt.madefor.cc/guides/canvas.html
Demonstrates how to add custom drawing operations to the canvas using `addCommand`. This example shows drawing text with specific foreground and background colors, and using `blit` for more efficient drawing.
```lua
-- Example of proper command usage
canvas:addCommand(function()
-- Draw red text on black background
canvas:drawText(1, 1, "Hello")
canvas:drawFg(1, 1, colors.red)
canvas:drawBg(1, 1, colors.black)
-- Or use blit for more efficient drawing
canvas:blit(1, 2, "Hello", "fffff", "00000") -- white on black
end)
```
--------------------------------
### Set Common Element Properties in Basalt (Lua)
Source: https://basalt.madefor.cc/guides/getting-started.html
This snippet illustrates how to set common properties for UI elements in Basalt, including position, size, background color, and foreground color. These methods can be chained to configure an element efficiently. The 'element' variable represents any Basalt UI object.
```lua
element:setPosition(x, y) -- Set position
element:setSize(width, height) -- Set size
element:setBackground(color) -- Set background color
element:setForeground(color) -- Set text color
```
--------------------------------
### Run Worm Program Example (Lua)
Source: https://basalt.madefor.cc/references/elements/Program.html
This Lua code snippet demonstrates how to create a button that, when clicked, opens a new window and executes the 'worm.lua' program within it using the Basalt library. It includes UI elements like frames, labels, and a close button.
```lua
local basalt = require("basalt")
local main = basalt.getMainFrame()
local execPath = "rom/programs/fun/worm.lua"
local btn = main:addButton({
x = 5,
y = 2,
width = 20,
height = 3,
text = "Run Worm",
}):onClick(function()
local frame = main:addFrame({
x = 2,
y = 2,
width = 28,
height = 10,
title = "Worm Program",
draggable = true,
})
:setDraggingMap({{x=1, y=1, width=27, height=1}})
:onFocus(function(self)
self:prioritize()
end)
local program = frame:addProgram({
x = 1,
y = 2,
width = 28,
height = 9,
})
program:execute(execPath)
frame:addLabel({
x = 2,
y = 1,
text = "Worm",
foreground = colors.lightBlue
})
frame:addButton({
x = frame.get("width"),
y = 1,
width = 1,
height = 1,
text = "X",
background = colors.red,
foreground = colors.white
}):onClick(function()
frame:destroy()
end)
end)
basalt.run()
```
--------------------------------
### Register Animation Start Callback
Source: https://basalt.madefor.cc/references/plugins/animation.html
Registers a callback function to be executed when the animation starts.
```lua
anim:onStart(function()
print("Animation started")
end)
```
--------------------------------
### Initialize and Populate Basalt Table in Lua
Source: https://basalt.madefor.cc/references/elements/Table.html
This snippet demonstrates how to create a new table instance, set its position, size, and define columns. It then populates the table with sample data, including names, ages, countries, and scores. The table's background and foreground colors are also customized.
```lua
local peopleTable = main:addTable()
:setPosition(1, 2)
:setSize(49, 10)
:setColumns({
{name = "Name", width = 15},
{name = "Age", width = 8},
{name = "Country", width = 12},
{name = "Score", width = 10}
})
:setBackground(colors.black)
:setForeground(colors.white)
peopleTable:addRow("Alice", 30, "USA", 95)
peopleTable:addRow("Bob", 25, "UK", 87)
peopleTable:addRow("Charlie", 35, "Germany", 92)
peopleTable:addRow("Diana", 28, "France", 88)
peopleTable:addRow("Eve", 32, "Spain", 90)
peopleTable:addRow("Frank", 27, "Italy", 85)
peopleTable:addRow("Grace", 29, "Canada", 93)
peopleTable:addRow("Heidi", 31, "Australia", 89)
peopleTable:addRow("Ivan", 26, "Russia", 91)
peopleTable:addRow("Judy", 33, "Brazil", 86)
peopleTable:addRow("Karl", 34, "Sweden", 84)
peopleTable:addRow("Laura", 24, "Norway", 82)
peopleTable:addRow("Mallory", 36, "Netherlands", 83)
peopleTable:addRow("Niaj", 23, "Switzerland", 81)
peopleTable:addRow("Olivia", 38, "Denmark", 80)
```
--------------------------------
### Initialize and Configure ProgressBar in Lua
Source: https://basalt.madefor.cc/references/elements/ProgressBar.html
Demonstrates how to create a progress bar instance, set its direction, and update its progress value. This is the primary method for integrating the progress bar into your application.
```lua
local progressBar = main:addProgressBar()
progressBar:setDirection("up")
progressBar:setProgress(50)
```
--------------------------------
### Property Initialization
Source: https://basalt.madefor.cc/guides/properties.html
Demonstrates how to initialize properties for an element when creating it, either by passing a table of properties or by chaining setter methods.
```APIDOC
## Property Initialization
### Description
Initialize properties for an element upon creation. This can be done by providing a table of key-value pairs or by chaining individual setter methods.
### Method
`addButton(properties_table)` or chaining setters
### Endpoint
N/A (Lua API)
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
`properties_table` (table) - Optional - A table containing properties to set (e.g., `x`, `y`, `width`, `height`, `text`).
### Request Example
```lua
-- Initialize multiple properties at creation
local button = main:addButton({
x = 5,
y = 5,
width = 10,
height = 3,
text = "Click me"
})
-- Equivalent using chained setters:
local button = main:addButton()
:setX(5)
:setY(5)
:setSize(10, 3)
:setText("Click me")
```
### Response
#### Success Response (200)
Returns the created element object.
#### Response Example
```lua
-- Returns the button element object
```
```
--------------------------------
### Initialize ComboBox Instance
Source: https://basalt.madefor.cc/references/elements/ComboBox.html
This function creates a new instance of the ComboBox component. It returns the newly created ComboBox object, ready to be configured and added to the UI.
```lua
ComboBox.new()
```
--------------------------------
### Combine Responsive and Reactive Systems in Lua
Source: https://basalt.madefor.cc/guides/responsive-system.html
Demonstrates combining Basalt's responsive and reactive plugins. The responsive plugin handles screen size changes, while reactive expressions within `:apply()` allow for dynamic property updates based on parent dimensions. No external dependencies are required beyond the Basalt library.
```lua
local frame = main:addFrame()
:setWidth("{parent.width * 0.8}") -- Reactive: 80% of parent
:responsive() -- Responsive: breakpoints
:when("parent.width < 30")
:apply({ background = colors.gray })
:otherwise({ background = colors.lightGray })
:setPropertyState("background", "hover", colors.white) -- State: hover effect
```
```lua
local element = main:addLabel()
:responsive()
:when("parent.width < 30")
:apply({ text = "Small", x = "{parent.width - self.width}" }) -- Reactive expression
:otherwise({ text = "Large", x = 5 })
```
--------------------------------
### Create and Use a Basalt Display in Lua
Source: https://basalt.madefor.cc/references/elements/Display.html
Demonstrates how to create a Basalt display element, set its properties, and use the ComputerCraft Window API for text manipulation. It also shows the use of the `paintutils` library for drawing.
```lua
-- Create a display for a custom terminal
local display = main:addDisplay()
:setSize(30, 10)
:setPosition(2, 2)
-- Get the window object for CC API operations
local win = display:getWindow()
-- Use standard CC terminal operations
win.setTextColor(colors.yellow)
win.setBackgroundColor(colors.blue)
win.clear()
win.setCursorPos(1, 1)
win.write("Hello World!")
-- Or use the helper method
display:write(1, 2, "Direct write", colors.red, colors.black)
-- Useful for external APIs
local paintutils = require("paintutils")
paintutils.drawLine(1, 1, 10, 1, colors.red, win)
```
--------------------------------
### Create a Simple UI with Basalt
Source: https://basalt.madefor.cc/home.html
This Lua code snippet demonstrates how to create a basic UI element, a button, using the Basalt framework. It sets the button's text, position, size, and defines an onClick event handler. The `basalt.run()` function is called to display the UI.
```lua
local basalt = require("basalt")
-- Create a simple UI
basalt.getMainFrame()
:addButton()
:setText("Hello Basalt!")
:setPosition(5, 5)
:setSize(14, 3)
:onClick(function()
-- Your code here
end)
basalt.run()
```
--------------------------------
### Get First Selected Item (Lua)
Source: https://basalt.madefor.cc/references/elements/Collection.html
Demonstrates how to get the first selected item in the Collection. This is useful when only one item is expected to be selected or when processing the primary selection. It returns the selected item.
```lua
local item = Collection:getSelectedItem()
```
--------------------------------
### Image:getMetadata()
Source: https://basalt.madefor.cc/references/elements/Image.html
Gets the metadata associated with the image.
```APIDOC
## Image:getMetadata()
### Description
Gets the metadata of the image.
### Returns
* `table` - The image metadata.
```
--------------------------------
### Advanced Responsive Layout Conditions in Lua
Source: https://basalt.madefor.cc/guides/responsive-system.html
Demonstrates advanced responsive layout conditions using Lua, including math operations and referencing element properties within string expressions.
```lua
local dynamicFrame = frame:addFrame()
:responsive()
:when("parent.width < parent.height")
:apply({ width = "parent.width * 0.9", height = 10 })
:otherwise({ width = 20, height = "parent.height * 0.9" })
```
--------------------------------
### Image:getFrame()
Source: https://basalt.madefor.cc/references/elements/Image.html
Gets the data for a specific frame of the image animation.
```APIDOC
## Image:getFrame()
### Description
Gets the specified frame.
### Returns
* `table` - The frame data.
```
--------------------------------
### Dynamic Element Positioning and Sizing with Basalt
Source: https://basalt.madefor.cc/guides/faq.html
Demonstrates how to dynamically position and size UI elements using string-based calculations relative to parent dimensions or function calls in Lua for Basalt. This allows for responsive UIs that adapt to screen resizes.
```lua
element:setPosition("{parent.width - 5}", 5) -- 5 from right edge
element:setSize("{parent.width - 10}", 5) -- 5 padding on each side
element:setPosition(function(self)
return self:getParent() - 5
end, 5) -- Another example, but as function call
```
--------------------------------
### Dynamic Sizing with Reactive Plugin in Lua
Source: https://basalt.madefor.cc/guides/responsive-system.html
Demonstrates dynamic sizing based on text content using the Reactive Plugin in Lua. The label's width adjusts automatically with its text length plus padding.
```lua
local label = frame:addLabel()
:setText("Dynamic width")
:setWidth("{#self.text + 2}") -- Width = text length + padding
```
--------------------------------
### Image:getPixelData(x, y)
Source: https://basalt.madefor.cc/references/elements/Image.html
Gets pixel information at a specific position (x, y).
```APIDOC
## Image:getPixelData(x, y)
### Description
Gets pixel information at position.
### Parameters
* `x` (number) - X position.
* `y` (number) - Y position.
### Returns
* `fg` (Foreground) - Foreground color.
* `bg` (Background) - Background color.
* `char` (Character) - Character at position.
```
--------------------------------
### Initialize Basalt Element Properties
Source: https://basalt.madefor.cc/guides/properties.html
Demonstrates two ways to initialize properties when creating Basalt elements: using a table of properties or chaining setter methods. The table method is concise for multiple properties, while the chained method offers a step-by-step approach.
```lua
-- Initialize multiple properties at creation
local button = main:addButton({
x = 5,
y = 5,
width = 10,
height = 3,
text = "Click me"
})
-- Equivalent to:
local button = main:addButton()
:setX(5)
:setY(5)
:setSize(10, 3)
:setText("Click me")
```
--------------------------------
### Basic Reactive Plugin Usage in Lua
Source: https://basalt.madefor.cc/guides/responsive-system.html
Shows basic usage of the Reactive Plugin in Lua for dynamic property values. It demonstrates centering a label and setting a progress bar width based on expressions.
```lua
-- Center a label horizontally
local label = frame:addLabel()
:setText("Centered")
:setX("{parent.width / 2 - self.width / 2}")
-- Progress bar that takes 80% of parent width
frame:addProgressBar()
:setWidth("{parent.width * 0.8}")
:setX("{parent.width * 0.1}")
```