docs: render references from source metadata

This commit is contained in:
Zef Hemel
2026-07-16 12:07:56 +02:00
parent 75ca3b9c39
commit 8e004812bc
29 changed files with 109 additions and 2633 deletions
+1 -52
View File
@@ -8,55 +8,4 @@ references:
The Asset API provides functions for reading and managing assets embedded in plugs.
### asset.readAsset(plugName, name, encoding?)
Reads an asset embedded in a plug.
Parameters:
- `plugName`: Name of the plug to read asset from
- `name`: Name of the asset to read
- `encoding`: Optional encoding type, either "utf8" (default) or "dataurl"
Returns the content of the asset in the requested encoding.
Example:
```lua
-- Read a text file as UTF-8
local text = asset.readAsset("myplug", "data.txt")
print(text)
-- Read an image as data URL
local imageData = asset.readAsset("myplug", "image.png", "dataurl")
print(imageData)
```
### asset.listFiles(plugName)
Lists all files in a plug.
Parameters:
- `plugName`: Name of the plug to list files from
Returns an array of FileMeta objects containing information about each file.
Example:
```lua
local files = asset.listFiles("myplug")
for _, file in ipairs(files) do
print(file.name, file.size)
end
```
### asset.getFileMeta(plugName, name)
Gets metadata about a specific file in a plug.
Parameters:
- `plugName`: Name of the plug
- `name`: Name of the file to get metadata for
Returns a FileMeta object containing information about the file.
Example:
```lua
local meta = asset.getFileMeta("myplug", "data.txt")
print("File size:", meta.size)
print("Last modified:", meta.lastModified)
```
${spacelua.renderApiDocumentation("asset")}
+1 -24
View File
@@ -7,27 +7,4 @@ references:
The Client Store API provides a simple key-value store for client-specific states and preferences.
## clientStore.set(key, value)
Sets a value in the client store.
Example:
```lua
clientStore.set("theme", "dark")
```
## clientStore.get(key)
Gets a value from the client store.
Example:
```lua
local theme = clientStore.get("theme")
print("Current theme: " .. theme)
```
## clientStore.del(key)
Deletes a value from the client store.
Example:
```lua
clientStore.del("theme")
```
${spacelua.renderApiDocumentation("clientStore")}
+1 -7
View File
@@ -9,10 +9,4 @@ references:
The Code Widget API provides functions for managing code widgets in the editor.
### codeWidget.refreshAll()
Refreshes all code widgets on the current page that support refreshing.
Example:
```lua
codeWidget.refreshAll() -- Refresh all code widgets on the page
```
${spacelua.renderApiDocumentation("codeWidget")}
+18 -101
View File
@@ -9,119 +9,36 @@ references:
The Config API provides functions for managing configuration values, defining their JSON schemas, and exposing them in the [[Configuration Manager]] UI.
### config.get(path, defaultValue)
Gets a config value by path, with support for dot notation.
${spacelua.renderApiDocumentation("config")}
Parameters:
- `path`: The path to get the value from
- `defaultValue`: The default value to return if the path doesn't exist
## Configuration Manager guide
Example:
```lua
local theme = config.get("theme", "light")
print("Current theme: " .. theme)
```
### config.set(path, value)
Sets a config value by path, with support for dot notation.
Parameters:
- `path`: The path to set the value at
- `value`: The value to set
Example:
```lua
config.set("theme", "dark")
```
### config.set(values)
Sets multiple config values at once.
Parameters:
- `values`: An object containing key-value pairs to set
Example:
```lua
config.set({
theme = "dark",
fontSize = 14
})
```
### config.has(path)
Checks if a config path exists.
Parameters:
- `path`: The path to check
Example:
```lua
if config.has("theme") then
print("Theme is configured")
end
```
### config.define(key, schema)
Defines a JSON schema for a configuration key. The schema is used to validate values when setting this key, and (with the right annotations) to surface the option in the [[Configuration Manager]].
Parameters:
- `key`: The configuration key to define a schema for (dot notation supported for nested keys)
- `schema`: The JSON schema to validate against
Two extensions on top of plain JSON Schema:
Schemas registered through `config.define` support two extensions on top of plain JSON Schema:
* `default`: when present, the value is automatically applied if the key is not already set.
* `ui` (optional): annotations that opt this field into the [[Configuration Manager]] UI. See below.
* `ui`: optional annotations that expose the field in the [[Configuration Manager]].
Example:
### `ui` annotations
```lua
config.define("shortWikiLinks", {
description = "Render wiki links to just the last segment, e.g. Person/John becomes John",
type = "boolean",
default = true,
ui = { category = "Editor", label = "Short wiki links", priority = 1 },
})
```
Only fields that have a `ui` attribute appear in the [[Configuration Manager]]. Recognized properties:
#### `ui` annotations
Only fields that have a `ui` attribute set appear in the [[Configuration Manager]]. Recognized properties:
* `category` (required): name of the category (tab) the field appears under. Should match a `config.defineCategory` name (otherwise the category appears at the bottom in alphabetical order).
* `label`: Human-readable label shown next to the control.
* `priority`: Number used to sort fields within a category (descending — higher `priority` appears first). Fields without `priority` sort as `0`.
* `inputType`: For `string` fields: set to `"password"` to render a masked input.
* `category` (required): name of the category (tab) the field appears under. It should match a `config.defineCategory` name; otherwise the category appears at the bottom in alphabetical order.
* `label`: human-readable label shown next to the control.
* `priority`: number used to sort fields within a category in descending order. Fields without a priority sort as `0`.
* `inputType`: for `string` fields, set this to `"password"` to render a masked input.
The control shown depends on the schema `type`:
* `boolean`: Checkbox
* `string` with `enum`: Dropdown
* `string`: Text input (or password input if `ui.inputType = "password"`)
* `number`: Number input
* Anything else: A "Configure manually in CONFIG" hint (the user has to edit the [[CONFIG]] page directly)
* `boolean`: checkbox
* `string` with `enum`: dropdown
* `string`: text input, or password input when `ui.inputType` is `"password"`
* `number`: number input
* Anything else: a "Configure manually in CONFIG" hint; the user must edit the [[CONFIG]] page directly
The field's `description` is shown as helper text below the label.
Nested schemas can carry their own `ui` annotations — when a parent object's children all have `ui` set, the parent itself is skipped and each child surfaces as an individual field. This is how related options (like `smartQuotes.double.left`, `smartQuotes.double.right`, …) end up as separate rows in the same category.
Nested schemas can carry their own `ui` annotations. When a parent object's children all have `ui` set, the parent itself is skipped and each child appears as an individual field. This is how related options such as `smartQuotes.double.left` and `smartQuotes.double.right` become separate rows in the same category.
### config.defineCategory(definition)
Registers (or updates) a UI category for the [[Configuration Manager]]. Categories appear in the UI in descending `priority` (higher first); categories that are referenced by a schema's `ui.category` but never registered fall to the bottom in alphabetical order.
### Categories
Parameters:
- `definition`: an object with the following fields:
- `name` (required): the category name; must match the value used in schemas' `ui.category`.
- `description` (optional): a short description shown at the top of the category.
- `priority` (optional): number controlling the order categories appear in (descending — higher first).
Example:
```lua
config.defineCategory {
name = "Editor",
description = "Behavior of the page editor: brackets, wiki link rendering, emoji aliases, and similar editing affordances.",
priority = 50,
}
```
### config.getCategories()
Returns the map of currently registered category definitions, keyed by `name`. Mostly useful for the Configuration Manager itself; rarely needed in user code.
Registered categories appear in descending `priority`, with higher values first. A category's optional `description` appears at the top of the category. Categories referenced by a schema but never registered appear after registered categories in alphabetical order.
+1 -60
View File
@@ -11,63 +11,4 @@ The Datastore API provides functions for interacting with a key-value store that
* **Keys** are represented as a list (Lua table) of strings.
* **Values** can be any persistable value.
# Key-Value Operations
## datastore.set(key, value)
Sets a value in the key-value store.
Example:
```lua
datastore.set({"user","123"}, {name = "John", age = 30})
```
## datastore.get(key)
Gets a value from the key-value store.
Example:
```lua
local user = datastore.get({"user","123"})
print(user.name) -- prints "John"
```
## datastore.del(key)
Deletes a value from the key-value store.
Example:
```lua
datastore.del({"user", "123"})
```
# Batch Operations
## datastore.batchSet(kvs)
Sets multiple key-value pairs in a single operation.
Example:
```lua
local kvs = {
{key = {"user", "1"}, value = {name = "Alice"}},
{key = {"user", "2"}, value = {name = "Bob"}}
}
datastore.batchSet(kvs)
```
## datastore.batchGet(keys)
Gets multiple values in a single operation.
Example:
```lua
local keys = {{"user", "1"}, {"user", "2"}}
local values = datastore.batchGet(keys)
for _, value in ipairs(values) do
print(value.name)
end
```
## datastore.batchDel(keys)
Deletes multiple values in a single operation.
Example:
```lua
local keys = {{"user", "1"}, {"user", "2"}}
datastore.batchDel(keys)
${spacelua.renderApiDocumentation("datastore")}
+1 -458
View File
@@ -9,461 +9,4 @@ references:
The Editor API provides functions for interacting with the editor interface.
### editor.getCurrentPage()
Returns the [[Names|name]] of the page (or document) currently open in the editor.
Example: ${editor.getCurrentPage()}
### editor.getCurrentPageMeta()
Returns the meta data of the page (or document) currently open in the editor.
Example:
${editor.getCurrentPageMeta()}
### editor.getCurrentPath()
Returns the [[Paths|path]] of the page or document currently open in the editor.
Example:
${editor.getCurrentPath()}
### editor.getCurrentEditor()
Returns the name of the currently open editor.
Example:
```lua
local editorName = editor.getCurrentEditor()
print(editorName)
```
### editor.getText()
Returns the full text of the currently open page.
Example:
```lua
local text = editor.getText()
print("Document length: " .. #text)
```
### editor.getCurrentLine()
Returns the current line range and text.
Example:
```lua
local line = editor.getCurrentLine()
print("from " .. line.from .. " to " .. line.to .. " text " .. line.text .. " text with cursor " .. line.textWithCursor)
```
### editor.setText(text, isolateHistory)
Updates the editor text while preserving cursor location.
Example:
```lua
local text = editor.getText()
editor.setText(text:upper(), false) -- Convert to uppercase
```
### editor.insertAtPos(text, pos)
Insert text at the specified position.
Example:
```lua
editor.insertAtPos("Hello!", 0) -- Insert at beginning
```
### editor.replaceRange(from, to, text)
Replace text in the specified range.
Example:
```lua
editor.replaceRange(0, 5, "New text")
```
### editor.insertAtCursor(text, scrollIntoView?)
Insert text at the current cursor position.
Example:
```lua
editor.insertAtCursor("Inserted at cursor")
```
### editor.getCursor()
Returns the cursor position as character offset.
Example:
```lua
local pos = editor.getCursor()
print("Cursor at position: " .. pos)
```
### editor.getSelection()
Returns the current selection range.
Example:
```lua
local sel = editor.getSelection()
print("Selection from " .. sel.from .. " to " .. sel.to)
```
### editor.setSelection(from, to)
Sets the current selection range.
Example:
```lua
editor.setSelection(0, 10) -- Select first 10 characters
```
### editor.moveCursor(pos, center)
Move the cursor to a specific position.
Example:
```lua
editor.moveCursor(0, true) -- Move to start and center
```
### editor.moveCursorToLine(line, column, center)
Move the cursor to a specific line and column.
Example:
```lua
editor.moveCursorToLine(1, 1, true) -- Move to start of first line
```
### editor.invokeCommand(name, args?)
Invokes a client command by name.
Example:
```lua
editor.invokeCommand("Stats: Show")
```
### editor.save()
Force saves the current page.
Example:
```lua
editor.save()
```
### editor.navigate(ref, replaceState?, newWindow?)
Navigates to the specified page reference.
Parameters:
- `ref`: The (string) reference to navigate to, see [[../Link#Link syntax (String refs)|string refs]]
- `replaceState`: Whether to replace the current history state
- `newWindow`: Whether to open in a new window
Example:
```lua
editor.navigate("CHANGELOG@123")
```
### editor.open(ref, replaceState?, newWindow?)
Opens the specified page reference. Unlike `editor.navigate`, which always opens
the page fresh (at the top, or at an explicit pointer such as `#header`/`@pos`),
`editor.open` does a best-effort restore of the cursor and scroll position you
last had on that page during this session. An explicit pointer in the ref still
takes precedence.
Parameters:
- `ref`: The (string) reference to open, see [[../Link#Link syntax (String refs)|string refs]]
- `replaceState`: Whether to replace the current history state
- `newWindow`: Whether to open in a new window
Example:
```lua
editor.open("CHANGELOG")
```
### editor.openPageNavigator(mode)
Opens the page navigator.
Example:
```lua
editor.openPageNavigator("page")
```
### editor.openCommandPalette()
Opens the command palette.
Example:
```lua
editor.openCommandPalette()
```
### editor.reloadPage()
Force reloads the current page.
Example:
```lua
editor.reloadPage()
```
### editor.reloadUI()
Force reloads the browser UI.
Example:
```lua
editor.reloadUI()
```
### editor.rebuildEditorState()
Rebuilds the editor state to ensure the dispatch updates the state.
Example:
```lua
editor.rebuildEditorState()
```
### editor.reloadConfigAndCommands()
Reloads the config and commands, also in the server.
Example:
```lua
editor.reloadConfigAndCommands()
```
### editor.openUrl(url, existingWindow?)
Opens the specified URL in the browser.
Example:
```lua
editor.openUrl("https://example.com")
```
### editor.newWindow()
Opens a new window.
Example:
```lua
editor.newWindow()
```
### editor.goHistory(delta)
Moves in the browser history.
Example:
```lua
editor.goHistory(-1) -- Go back
```
### editor.showPanel(id, mode, html, script)
Shows a panel in the editor.
Example:
```lua
editor.showPanel("rhs", 1, "<h1>Hello</h1>")
```
### editor.hidePanel(id)
Hides a panel in the editor.
Example:
```lua
editor.hidePanel("rhs")
```
### editor.flashNotification(message, type, options?)
Shows a flash notification.
Parameters:
- `message`: The message to display
- `type`: Notification type — `"info"` (default), `"error"`, or `"warning"`
- `options` (optional): Table with additional options:
- `timeout`: Dismiss timeout in milliseconds. Use `0` for persistent notifications (default: 4000/5000/8000 depending on type)
- `actions`: List of action buttons, each with:
- `name`: Button label
- `run`: Function to call when clicked (auto-dismisses the notification)
Example:
```lua
-- Simple notification
editor.flashNotification("Operation completed", "info")
-- Persistent notification with action button
editor.flashNotification("Update available", "warning", {
timeout = 0,
actions = {
{
name = "Reload",
run = function()
editor.reloadUI()
end
}
}
})
```
### editor.downloadFile(filename, dataUrl)
Triggers a file download in the browser.
Example:
```lua
editor.downloadFile("test.txt", "data:text/plain;base64,SGVsbG8=")
```
### editor.uploadFile(accept, capture)
Opens a file upload dialog.
Example:
```lua
local file = editor.uploadFile(".txt", nil)
print("Uploaded: " .. file.name)
```
### editor.copyToClipboard(data)
Copies data to the clipboard.
> **note** Note
> Requires HTTPS, see [[Install/Network and Internet]]
Example:
```lua
editor.copyToClipboard("Copied text")
```
### editor.filterBox(label, options, helpText?, placeHolder?)
Shows a filter box UI.
Example:
```lua
local result = editor.filterBox("Select:", {
{ name="Option 1", value="1" },
{ name="Option 2", value="2", description="More details about 2" }
})
```
### editor.toggleFold()
Toggles code folding at the current position.
Example:
```lua
editor.toggleFold()
```
### editor.foldAll()
Folds all foldable regions.
Example:
```lua
editor.foldAll()
```
### editor.unfoldAll()
Unfolds all folded regions.
Example:
```lua
editor.unfoldAll()
```
### editor.undo()
Undoes the last change.
Example:
```lua
editor.undo()
```
### editor.redo()
Redoes the last undone change.
Example:
```lua
editor.redo()
```
### editor.openSearchPanel()
Opens the editor's search panel.
Example:
```lua
editor.openSearchPanel()
```
### editor.deleteLine()
Deletes the current line.
Example:
```lua
editor.deleteLine()
```
### editor.toggleComment()
Comments or uncomments the current line.
Example:
```lua
editor.toggleComment()
```
### editor.moveLineUp()
Moves the current line up.
Example:
```lua
editor.moveLineUp()
```
### editor.moveLineDown()
Moves the current line down.
Example:
```lua
editor.moveLineDown()
```
### editor.vimEx(exCommand)
Executes a Vim ex command.
Example:
```lua
editor.vimEx(":w")
```
### editor.sendMessage(type, data?)
Sends a message to the editor.
Example:
```lua
editor.sendMessage("custom-event", { data: "value" })
```
### editor.prompt(message, defaultValue?)
Shows a prompt dialog.
Example:
```lua
local result = editor.prompt("Enter your name:", "John")
```
### editor.confirm(message)
Shows a confirmation dialog.
Example:
```lua
local confirmed = editor.confirm("Are you sure?")
```
### editor.alert(message)
Shows an alert dialog.
Example:
```lua
editor.alert("Operation completed")
```
### editor.getUiOption(key)
Gets a UI option value.
Example:
```lua
local theme = editor.getUiOption("theme")
```
### editor.setUiOption(key, value)
Sets a UI option value.
Example:
```lua
editor.setUiOption("theme", "dark")
```
${spacelua.renderApiDocumentation("editor")}
+2 -12
View File
@@ -4,16 +4,6 @@ references:
- client/space_lua/stdlib/encoding.ts
---
The `encoding` API implements a few useful functions to handle various types of encoding.
The `encoding` namespace converts between strings, byte buffers, Base64, and UTF-8.
### encoding.base64Encode(data)
Encodes data (either a string or byte buffer) as a base64 encoded string.
### encoding.base64Decode(s)
Decodes a base64 encoded string into a byte buffer.
### encoding.utf8Encode(s)
Encodes a (UTF-8) string into a byte buffer.
### encoding.utf8Decode(data)
Decodes a byte buffer into a (UTF-8) string.
${spacelua.renderApiDocumentation("encoding")}
+1 -39
View File
@@ -8,42 +8,4 @@ references:
The Event API provides functions for working with SilverBullet's event bus system, allowing communication between different parts of the application.
# API
### event.listen(listenerDef)
Register an event listener.
```lua
event.listen {
name = "my-event",
run = function(e)
print("Data", e.data)
end
}
```
### event.dispatch(eventName, data, timeout)
Triggers an event on the SilverBullet event bus. Event handlers can return values, which are accumulated and returned to the caller.
Example:
```lua
-- Simple event dispatch
event.dispatch("custom.event", {message = "Hello"})
-- Event dispatch with timeout and response handling
local responses = event.dispatch("data.request", {id = 123}, 5000)
for _, response in ipairs(responses) do
print(response)
end
```
### event.listEvents()
Lists all events currently registered (listened to) on the SilverBullet event bus.
Example:
```lua
local events = event.listEvents()
for _, eventName in ipairs(events) do
print("Registered event: " .. eventName)
end
```
${spacelua.renderApiDocumentation("event")}
+2 -220
View File
@@ -5,224 +5,6 @@ references:
- client/space_lua/runtime.ts
---
These are Lua functions defined in the global namespace:
These functions are defined in the global namespace. Alongside standard Lua functions, Space Lua provides the `each` and `some` convenience functions.
# Standard Lua
## print(...)
Prints to your log (browser or server log).
Example:
```lua
print("Hello, world!")
```
## assert(expr, message?)
Asserts `expr` to be true otherwise raises an [[#error(message)]]
Example:
```lua
assert(1 == 2, "1 is not equal to 2")
```
## ipairs
Returns an iterator for array-like tables that iterates over numeric indices in order.
Example:
```lua
local fruits = {"apple", "banana", "orange"}
for i, fruit in ipairs(fruits) do
print(i, fruit)
end
-- Output:
-- 1 apple
-- 2 banana
-- 3 orange
```
## pairs
Returns an iterator for tables that traverses all keys and values.
Example:
```lua
local person = {name = "John", age = 30, city = "New York"}
for key, value in pairs(person) do
print(key, value)
end
-- Output (order not guaranteed):
-- name John
-- age 30
-- city New York
```
## unpack
Unpacks a table into individual values.
Example:
```lua
local numbers = {10, 20, 30}
print(unpack(numbers)) -- prints: 10 20 30
local function sum(a, b, c)
return a + b + c
end
print(sum(unpack(numbers))) -- prints: 60
```
## type
Returns the type of a value as a string.
Example:
```lua
print(type("hello")) -- string
print(type(42)) -- number
print(type({})) -- table
print(type(print)) -- function
print(type(nil)) -- nil
print(type(true)) -- boolean
```
## tostring
Converts a value to a string representation.
Example:
```lua
print(tostring(42)) -- "42"
print(tostring(true)) -- "true"
print(tostring({1, 2, 3})) -- "{1, 2, 3}"
```
## tonumber
Converts a string to a number, returns nil if conversion fails.
Example:
```lua
print(tonumber("42")) -- 42
print(tonumber("3.14")) -- 3.14
print(tonumber("abc")) -- nil
```
## error(message)
Throw an error.
Example:
```lua
error("FAIL")
```
## pcall
Protected call - executes a function in protected mode, catching errors.
Example:
```lua
local status, result = pcall(function()
return 10/0 -- will cause an error
end)
print(status) -- false
print(result) -- "attempt to divide by zero"
status, result = pcall(function()
return 10/2 -- will succeed
end)
print(status) -- true
print(result) -- 5
```
## xpcall
Like pcall, but allows you to specify an error handler function.
Example:
```lua
local function errorHandler(err)
return "Error occurred: " .. tostring(err)
end
local status, result = xpcall(function()
error("something went wrong")
end, errorHandler)
print(status) -- false
print(result) -- "Error occurred: something went wrong"
```
## setmetatable
Sets the metatable for a table.
Example:
```lua
local t1 = {value = 10}
local t2 = {value = 20}
local mt = {
__add = function(a, b)
return a.value + b.value
end
}
setmetatable(t1, mt)
setmetatable(t2, mt)
-- Now we can add the tables together using the + operator
print(t1 + t2) -- prints: 30
```
## getmetatable
Gets the metatable of a table.
Example:
```lua
local t = {}
local mt = {}
setmetatable(t, mt)
print(getmetatable(t) == mt) -- true
```
## rawset
Sets a table index without invoking metamethods.
Example:
```lua
local t = {}
local mt = {
__newindex = function(t, k, v)
print("Blocked setting:", k, v)
end
}
setmetatable(t, mt)
t.foo = "bar" -- prints: "Blocked setting: foo bar"
rawset(t, "foo", "bar") -- bypasses the metamethod
print(t.foo) -- prints: "bar"
```
## dofile(path)
Loads a Lua file from a path in your space, e.g. if you uploaded a `test.lua` file, you can load it with `dofile("test.lua")`.
# Non-standard Extensions
## each
Returns an iterator for array-like tables that iterates over values only (without indices).
Example:
```lua
local fruits = {"apple", "banana", "orange"}
for fruit in each(fruits) do
print(fruit)
end
-- Output:
-- apple
-- banana
-- orange
```
## some
Returns nil if the value is empty, otherwise returns the value unchanged. Empty tables, strings containing only whitespace, `inf` and `nan` numeric value are considered empty.
Example:
```lua
print(some("hello")) -- hello
print(some("")) -- nil
print(some(" ")) -- nil
print(some({})) -- nil
print(some(0)) -- 0
print(some(1/0)) -- nil
print(some({}) or "empty") -- empty
```
${spacelua.renderApiDocumentation()}
+1 -2
View File
@@ -10,5 +10,4 @@ HTTP APIs
> **warning** Warning
> Deprecated: use [[API/net]] instead.
### http.request(url, options?)
Deprecated, use [[API/net#net.proxyFetch(url, options?)]] instead.
${spacelua.renderApiDocumentation("http")}
+9 -133
View File
@@ -6,157 +6,33 @@ references:
- client/data/object_index.ts
---
The `index` API provides convient functions for interacting with SilverBullet's [[Object Index]], allowing you to query indexed data.
The `index` API provides functions for interacting with SilverBullet's [[Object Index]], including query collections used by [[Space Lua/Integrated Query]], schema introspection, ad-hoc Markdown indexing, and direct object-index operations.
# Query collection APIs
(to be used with [[Space Lua/Integrated Query]])
The main query API is `index.objects`; the other collection functions are mostly convenient filters over the same index.
The main API here is `index.objects`, the rest are mostly convenience wrappers around it.
${spacelua.renderApiDocumentation("index")}
## index.objects(tag)
Returns all objects carrying `tag` as a tag as a query collection.
## Integrated Query examples
Example:
${query[[from index.objects("page") limit 1]]}
Query one page:
## index.pages(tag?)
Returns all [[Object/page]]s as a query collection. Optionally filtered `tag`.
Example:
${query[[from index.pages() limit 1]]}
## index.subPages(pageName)
Returns all sub-pages of `pageName` (pages whose name starts with `${pageName}/`) as a query collection.
Query three sub-pages below the API page:
Example:
${query[[from p = index.subPages("API") limit 3 select p.name]]}
## index.contentPages(tag?)
Returns all content [[Object/page]]s (all pages excluding [[Meta Page|Meta Pages]]) as a query collection. Optionally filtered by an additional `tag`.
Render three incomplete tasks:
Example:
${query[[from index.contentPages() limit 1]]}
## index.metaPages()
Returns all [[Meta Page|Meta Pages]] as a query collection.
Example:
${query[[from index.metaPages() limit 1]]}
## index.aspiringPages()
Returns all [[Object/aspiring-page]]s (pages that are linked to but not yet created) as a query collection.
Example:
${query[[from index.aspiringPages() limit 3]]}
## index.tasks(tag?)
Returns [[Object/task]] as a query collection. Optionally filtered by an additional `tag`.
Example:
${query[[from t = index.tasks() where not t.done limit 3 select templates.taskItem(t)]]}
## index.headers(tag?)
Returns all [[Object/header]]s in your space as a query collection. Optionally filtered by an additional `tag`.
Ad-hoc index a Markdown fragment and select its list items:
Example:
${query[[from index.headers() limit 3]]}
## index.items(tag?)
Returns all [[Object/item]]s as a query collection. Optionally filtered by an additional `tag`.
Example:
${query[[from index.items() limit 3]]}
## index.paragraphs(tag?)
Returns all indexed [[Object/paragraph]]s as a query collection (note that by default only tagged paragraphs are indexed). Optionally filtered by an additional `tag`.
Example:
${query[[from index.paragraphs() limit 3]]}
## index.tables(tag?)
Returns all [[Object/table]] rows as a query collection. Optionally filtered by an additional `tag`.
Example:
${query[[from index.tables() limit 3]]}
## index.documents()
Returns all [[Object/document]]s as a query collection.
Example:
${query[[from index.documents() limit 3]]}
## index.links()
Returns all [[Object/link]]s as a query collection.
Example:
${query[[from index.links() limit 3]]}
## index.tags()
Returns all [[Object/tag]] objects as a query collection.
Example:
${query[[from index.tags() limit 3]]}
# Schema introspection APIs
## index.describeSchema()
Returns a map of tag name → raw JSON Schema for every defined object type / [[Tag]] that declares a schema. Tags without a schema are omitted. Use it to discover what attributes a tag's objects carry before querying them.
## index.tagSchema(tag)
Returns the raw JSON Schema for a single tag, or `nil` if the tag is not defined or has no schema.
# Indexing APIs
## index.markdown(text, pageMeta?)
Ad-hoc indexes `text` (represented as a markdown string) in memory, and returns all objects found there for further query. When no `pageMeta` is supplied dummy (empty) values will be used.
Example:
${query[[
from index.markdown("* Item 1\n* [ ] Task 1")
where _.tag == "item"
]]}
## index.indexObjects(page, objects)
Indexes an array of objects for a specific page and stores it in the data store.
`index.extractFrontmatter` can inspect and optionally transform frontmatter and top-level tags. For example, this returns the frontmatter of the current page:
Example:
```lua
local objects = {
{tag = "mytask", ref="task1", content = "Buy groceries"},
{tag = "mytask", ref="task2", content = "Write docs"}
}
index.indexObjects("my page", objects)
```
## index.queryLuaObjects(tag, query, scopedVariables?)
Queries objects using a Lua-based collection query.
Example:
```lua
local tasks = index.queryLuaObjects("mytask", {limit=3})
```
## index.getObjectByRef(page, tag, ref)
Retrieves a specific object by its reference.
Example:
```lua
local task = index.getObjectByRef("my page", "mytask", "task1")
if task then
print("Found task: " .. task.content)
end
```
## index.extractFrontmatter(text, extractOptions)
Extracts frontmatter from a markdown document (whose text is provided as argument), possibly cleaning it up. It also parses top-level tags consistent with SilverBullet's tag indexing system.
It returns a table with two keys:
- `frontmatter`: A table containing the parsed frontmatter.
- `text`: The text of the document, with any changes applied requested with the `extractOptions`.
The `extractOptions` is an optional table that can contain the following keys (which will affect the returned `text`):
- `removeKeys`: An array of keys to remove from the frontmatter.
- `removeTags`: A boolean or array of tags to remove from the frontmatter.
- `removeTagsPrefix`: An array of hierarchical tag prefixes whose body hashtag occurrences should be removed. A tag matches a prefix if it equals the prefix or starts with `${prefix}/`. For example, `{"meta/template"}` removes `#meta/template`, `#meta/template/page` and `#meta/template/slash`.
- `removeFrontMatterSection`: A boolean to remove the frontmatter section from the document.
Example applied to this page:
${(index.extractFrontmatter(editor.getText())).frontmatter}
+3 -83
View File
@@ -4,88 +4,8 @@ references:
- client/space_lua/stdlib/js.ts
---
API docs for Space Lua's `js` module, which provides JavaScript interoperability.
The `js` namespace provides JavaScript interoperability, including dynamic module imports, Lua/JavaScript value conversion, and asynchronous iterable support.
## js.import(url)
Imports a JavaScript module from a URL. Returns the imported module.
`js.importFromSpace` resolves a space-relative file path to the current space's same-origin `/.fs` URL. This lets a library import a JavaScript module shipped as a [[Frontmatter#files]] asset without constructing a deployment-specific base URL. A leading slash is optional, and a sole `default` export is unwrapped like `js.import`.
Example:
```lua
-- Import lodash library
local lodashLib = js.import("https://esm.sh/lodash@4.17.21")
local result = lodashLib.chunk({1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, 3)
-- Import moment.js for date handling
local momentLib = js.import("https://esm.sh/moment@2.30.1")
local dateObj = momentLib("1995-12-25")
print(dateObj.format("DD-MM-YYYY")) -- prints: 25-12-1995
```
## js.importFromSpace(path)
Like [[#js.import(url)]], but takes a path to a file in the current space (rather than a full URL) and resolves it to the file's same-origin `/.fs` URL before importing. This lets a library load a JavaScript module it ships as a [[Frontmatter#files]] asset without hand-building the base URL (which varies by where the space is hosted). A sole `default` export is unwrapped, just like `js.import`.
`path` is a space-relative path (a leading `/` is optional).
Example:
```lua
local acme = js.importFromSpace("Library/acme/acme.js")
acme.doSomething()
```
## js.new(constructor, ...)
Creates a new instance of a JavaScript class. Takes a constructor function and its arguments.
Example:
```lua
local DateClass = js.import("https://esm.sh/date-fns")
local dateObj = js.new(DateClass, "2024-03-14")
```
## js.stringify(value)
Converts a Lua value to a JSON string representation.
Example:
```lua
local dataArray = {1, 2, 3}
print(js.stringify(dataArray)) -- prints: [1,2,3]
local nestedArray = lodashLib.chunk({1, 2, 3, 4, 5, 6}, 2)
print(js.stringify(nestedArray)) -- prints: [[1,2],[3,4],[5,6]]
```
## js.tolua(value)
Converts a JavaScript value to its Lua equivalent.
Example:
```lua
local jsArray = someJsFunction()
local luaTable = js.tolua(jsArray)
```
## js.tojs(value)
Converts a Lua value to its JavaScript equivalent.
Example:
```lua
local luaTable = {1, 2, 3}
local jsArray = js.tojs(luaTable)
```
## js.log(...)
Logs messages to the JavaScript console.
Example:
```lua
js.log("Debug message")
js.log("User data:", {name = "John", age = 30})
```
## js.eachIterable(iterable)
Creates an iterator for JavaScript async iterables.
Example:
```lua
local asyncIterator = js.eachIterable(someJsAsyncIterable)
for value in asyncIterator do
print(value)
end
${spacelua.renderApiDocumentation("js")}
+1 -55
View File
@@ -7,58 +7,4 @@ references:
The JSON Schema API provides functions for validating JSON objects against JSON schemas.
## Validation Operations
### jsonschema.validateObject(schema, object)
Validates a JSON object against a JSON schema.
Example:
```lua
local schema = {
type = "object",
properties = {
name = {type = "string"},
age = {type = "number", minimum = 0}
},
required = {"name"}
}
local object = {name = "John", age = 30}
local error = jsonschema.validateObject(schema, object)
if error then
print("Validation error: " .. error)
else
print("Object is valid")
end
```
### jsonschema.inferFromObject(object)
Infers a best-effort JSON schema from the *shape* of a single sample value. Types are guessed from one example, so the result is a hint rather than a contract — the returned schema is marked with `"x-inferred": true`. Useful when an object type has no declared schema but you have an example to learn from.
Example:
```lua
local sample = { name = "Widget", count = 3, tags = { "a", "b" } }
local schema = jsonschema.inferFromObject(sample)
-- schema.properties.name.type == "string"
-- schema.properties.count.type == "integer"
-- schema.properties.tags.type == "array" (items.type == "string")
```
### jsonschema.validateSchema(schema)
Validates a JSON schema itself to ensure it's well-formed.
Example:
```lua
local schema = {
type = "object",
properties = {
name = {type = "string"}
}
}
local error = jsonschema.validateSchema(schema)
if error then
print("Schema error: " .. error)
else
print("Schema is valid")
end
${spacelua.renderApiDocumentation("jsonschema")}
+1 -26
View File
@@ -7,29 +7,4 @@ references:
The Language API provides functions for parsing code in various programming languages and listing supported languages.
## Language Operations
### language.parseLanguage(language, code)
Parses a piece of code using any of the supported SilverBullet languages.
Example:
```lua
local code = [[
function hello() {
console.log("Hello, world!");
}
]]
local tree = language.parseLanguage("javascript", [[
function hello() {
console.log("Hello, world!");
}
]])
print("Parsed syntax tree:", tree)
```
### language.listLanguages()
Lists all supported languages in fenced code blocks.
Example:
${language.listLanguages()}
${spacelua.renderApiDocumentation("language")}
+2 -63
View File
@@ -2,71 +2,10 @@
tags: api/syscall
references:
- plug-api/syscalls/lua.ts
- client/plugos/syscalls/lua.ts
- client/space_lua/syscalls.ts
- client/space_lua_api.ts
---
The Lua API provides functions for parsing and evaluating Lua code.
### lua.parseBlock(code)
Parses a string of Lua code (a block of statements) into an abstract syntax tree (AST).
Parameters:
- `code`: The Lua code to parse
Returns a LuaBlock object representing the parsed code.
Example:
```lua
local ast = lua.parseBlock("print('Hello')")
-- ast contains the parsed syntax tree
```
> **note** Note
> `lua.parse` is a deprecated alias for `lua.parseBlock` and is kept for backwards compatibility.
### lua.parseExpression(expression)
Parses a Lua expression into an abstract syntax tree (AST).
Parameters:
- `expression`: The Lua expression to parse
Returns a LuaExpression object representing the parsed expression.
Example:
```lua
local expr = lua.parseExpression("1 + 2 * 3")
-- expr contains the parsed expression tree
```
### lua.evalExpression(expression)
Evaluates a Lua expression and returns its result.
Parameters:
- `expression`: The Lua expression to evaluate
Returns the result of evaluating the expression.
Example:
```lua
local result = lua.evalExpression("1 + 2 * 3")
print(result) -- prints: 7
```
### lua.prettyPrintBlock(block, options?)
Pretty-prints a parsed Lua block AST (as returned by [[#lua.parseBlock(code)]]) back to formatted Lua source.
The optional `options` table accepts `indentWidth` (number, default `2`), `quote` (`"double"` or `"single"`, default `"double"`), and `trailingComma` (boolean, default `true`). Comments are not preserved.
Example:
```lua
local formatted = lua.prettyPrintBlock(lua.parseBlock("if a then return 1 end"))
```
### lua.prettyPrintExpression(expression, options?)
Pretty-prints a parsed Lua expression AST (as returned by [[#lua.parseExpression(expression)]]) back to formatted Lua source. Accepts the same `options` table as [[#lua.prettyPrintBlock(block, options?)]].
Example:
```lua
local formatted = lua.prettyPrintExpression(lua.parseExpression("{a=1,b=2}"))
```
${spacelua.renderApiDocumentation("lua")}
+1 -84
View File
@@ -9,87 +9,4 @@ references:
The Markdown API provides functions for parsing and rendering Markdown content.
## Markdown Operations
### markdown.parseMarkdown(text)
Parses a piece of markdown text into a ParseTree.
Example:
```lua
local text = [[
# Hello World
This is a **bold** statement.
]]
local tree = markdown.parseMarkdown(text)
print("Parsed markdown tree:", tree)
```
### markdown.renderParseTree(tree)
Renders a ParseTree back to markdown text.
Example:
```lua
local text = "# Title\n\nSome text"
local tree = markdown.parseMarkdown(text)
-- Modify tree if needed
local rendered = markdown.renderParseTree(tree)
print("Rendered markdown:", rendered)
```
### markdown.markdownToHtml(text)
Renders a piece of markdown text into HTML
Example:
```lua
local text = "# Title\n\nSome text"
local html = markdown.markdownToHtml(text)
print("Rendered html:", html)
```
### markdown.expandMarkdown(textOrTree, options?)
Expands custom markdown Lua directives and transclusions into plain markdown. Accepts either a markdown ParseTree or string.
Options (all default to `true`):
* `expandTransclusions`: Replace (markdown transclusions) with their content
* `expandLuaDirectives`: Replace Lua directives with their evaluated values
* `rewriteTasks`: Rewrite tasks to include references so that they can be updated
Example:
```lua
local text = "This is a some lua ${os.time()}"
print("Expanded markdown:", markdown.expandMarkdown(text))
```
### markdown.bakeSections(text, pageName?)
Re-bakes [[Baked Sections]] (`<!--#lua EXPR -->` ... `<!--/lua-->`) in `text` and returns the updated markdown.
Sections whose expression can’t produce portable markdown (an evaluation error, or an HTML-only widget) are left unchanged.
Example:
```lua
local text = [[
Total: <!--#lua 1 + 2 -->
old
<!--/lua-->
]]
-- Returns the text with the body refreshed to "3"
print(markdown.bakeSections(text))
```
### markdown.objectsToTable(data, options?)
Transforms a list of tables into a markdown table.
Supported options:
* `renderCell(val, key)` custom cell renderer
Example:
${markdown.objectsToTable({{name="Pete", age=20}, {name="Jane", age=32}}, {
renderCell=function(v, k)
if k == "age" and v > 20 then
return "*" .. v .. "*"
else
return v
end
end})}
${spacelua.renderApiDocumentation("markdown")}
+2 -232
View File
@@ -4,236 +4,6 @@ references:
- client/space_lua/stdlib/math.ts
---
API docs for Lua's `math` module.
The `math` namespace contains Lua-compatible numeric functions plus Space Lua's `cosineSimilarity` helper.
# Standard library
## math.random(m?, n?)
Returns a random number.
- `random()` returns a random float in range [0,1)
- `random(m)` returns a random integer in range [1,m]
- `random(m,n)` returns a random integer in range [m,n]
Example:
```lua
print(math.random()) -- prints: 0.123456789 (random float between 0 and 1)
print(math.random(10)) -- prints: 5 (random integer between 1 and 10)
print(math.random(5, 10)) -- prints: 7 (random integer between 5 and 10)
```
## math.abs(x)
Returns the absolute value of `x`.
Example:
```lua
print(math.abs(-5)) -- prints: 5
print(math.abs(5)) -- prints: 5
```
## math.ceil(x)
Returns the smallest integer greater than or equal to `x`.
Example:
```lua
print(math.ceil(4.2)) -- prints: 5
print(math.ceil(-4.2)) -- prints: -4
```
## math.floor(x)
Returns the largest integer less than or equal to `x`.
Example:
```lua
print(math.floor(4.8)) -- prints: 4
print(math.floor(-4.8)) -- prints: -5
```
Note: `math.floor(x + 0.5)` rounds to closest integer, similar to `round(x)` function from other languages
## math.max(...)
Returns the maximum value among its arguments.
Example:
```lua
print(math.max(1, 2, 3, 4, 5)) -- prints: 5
print(math.max(-10, -5, -1)) -- prints: -1
```
## math.min(...)
Returns the minimum value among its arguments.
Example:
```lua
print(math.min(1, 2, 3, 4, 5)) -- prints: 1
print(math.min(-10, -5, -1)) -- prints: -10
```
## math.fmod(x, y)
Returns the remainder of the division of `x` by `y` that rounds the quotient towards zero.
Example:
```lua
print(math.fmod(10, 3)) -- prints: 1
print(math.fmod(-10, 3)) -- prints: -1
```
## math.modf(x)
Returns two numbers, the integral part of `x` and the fractional part of `x`.
Example:
```lua
local intPart, fracPart = math.modf(3.14)
print(intPart, fracPart) -- prints: 3 0.14
```
## math.exp(x)
Returns the value e^x (where e is the base of natural logarithms).
Example:
```lua
print(math.exp(0)) -- prints: 1
print(math.exp(1)) -- prints: 2.7182818284590455
```
## math.log(x, base?)
Returns the logarithm of `x` in the given base. If base is not specified, returns the natural logarithm of `x`.
Example:
```lua
print(math.log(10)) -- prints: 2.302585092994046 (natural log)
print(math.log(100, 10)) -- prints: 2 (log base 10)
```
## math.pow(x, y)
Returns x^y.
Example:
```lua
print(math.pow(2, 3)) -- prints: 8
print(math.pow(10, 2)) -- prints: 100
```
## math.sqrt(x)
Returns the square root of `x`.
Example:
```lua
print(math.sqrt(16)) -- prints: 4
print(math.sqrt(2)) -- prints: 1.4142135623730951
```
## math.cos(x)
Returns the cosine of `x` (in radians).
Example:
```lua
print(math.cos(0)) -- prints: 1
print(math.cos(math.pi)) -- prints: -1
```
## math.sin(x)
Returns the sine of `x` (in radians).
Example:
```lua
print(math.sin(0)) -- prints: 0
print(math.sin(math.pi / 2)) -- prints: 1
```
## math.tan(x)
Returns the tangent of `x` (in radians).
Example:
```lua
print(math.tan(0)) -- prints: 0
print(math.tan(math.pi / 4)) -- prints: 1
```
## math.acos(x)
Returns the arc cosine of `x` (in radians).
Example:
```lua
print(math.acos(1)) -- prints: 0
print(math.acos(0)) -- prints: 1.5707963267948966 (pi/2)
```
## math.asin(x)
Returns the arc sine of `x` (in radians).
Example:
```lua
print(math.asin(0)) -- prints: 0
print(math.asin(1)) -- prints: 1.5707963267948966 (pi/2)
```
## math.atan(y, x?)
Returns the arc tangent of `y/x` (in radians). If `x` is not provided, returns the arc tangent of `y` (in radians).
Example:
```lua
print(math.atan(1)) -- prints: 0.7853981633974483 (pi/4)
print(math.atan(1, 1)) -- prints: 0.7853981633974483 (pi/4)
```
## math.cosh(x)
Returns the hyperbolic cosine of `x`.
Example:
```lua
print(math.cosh(0)) -- prints: 1
```
## math.sinh(x)
Returns the hyperbolic sine of `x`.
Example:
```lua
print(math.sinh(0)) -- prints: 0
```
## math.tanh(x)
Returns the hyperbolic tangent of `x`.
Example:
```lua
print(math.tanh(0)) -- prints: 0
```
## math.deg(x)
Converts angle `x` from radians to degrees.
Example:
```lua
print(math.deg(math.pi)) -- prints: 180
print(math.deg(math.pi/2)) -- prints: 90
```
## math.rad(x)
Converts angle `x` from degrees to radians.
Example:
```lua
print(math.rad(180)) -- prints: 3.141592653589793
print(math.rad(90)) -- prints: 1.5707963267948966
```
## math.ult(m, n)
Returns a boolean, true if integer `m` is below integer `n` when they are compared as unsigned integers.
Example:
```lua
print(math.ult(2, 3)) -- prints: true
print(math.ult(-1, 1)) -- prints: false (as unsigned integers)
```
# Non-standard Extensions
## math.cosineSimilarity(vecA, vecB)
Returns the cosine similarity between two vectors.
Example:
```lua
local vec1 = {1, 2, 3}
local vec2 = {4, 5, 6}
print(math.cosineSimilarity(vec1, vec2)) -- prints: 0.9746318461970762
```
${spacelua.renderApiDocumentation("math")}
+3 -64
View File
@@ -8,7 +8,10 @@ references:
The Message Queue API provides functions for implementing a simple message queue system.
${spacelua.renderApiDocumentation("mq")}
## Example
```space-lua
mq.subscribe {
queue = "testqueue",
@@ -24,67 +27,3 @@ mq.subscribe {
${widgets.button("Send message on queue", function()
mq.send("testqueue", "Hello world")
end)}
## API
### mq.subscribe(spec)
Subscribe to a queue. Spec keys:
* `queue`: name of the queue to subscribe to
* `batchSize`: maximum number of messages to ingest per run
* `autoAck`: (defaults to `true`), whether to automatically acknowledge a message if no error occurs during processing
* `run`: callback with the function to run, will receive a `messages` argument where each message is a table containing:
* `queue`: name of the queue the message was sent to
* `id`: message id
* `body`: message body
### mq.send(queue, body)
Sends a message to a queue.
Example:
```lua
mq.send("tasks", "my task")
```
### mq.batchSend(queue, bodies)
Sends multiple messages to a queue in a single operation.
Example:
```lua
mq.batchSend("tasks", {"task 1", "task 2" })
```
### mq.ack(queue, id)
Acknowledges a message from a queue, marking it as processed.
Example:
```lua
mq.ack("tasks", "message-123")
```
### mq.batchAck(queue, ids)
Acknowledges multiple messages from a queue in a single operation.
Example:
```lua
mq.batchAck("tasks", {"msg1", "msg2", "msg3"})
```
## Queue Management
### mq.getQueueStats(queue)
Retrieves statistics about a particular queue.
Example:
```lua
local stats = mq.getQueueStats("tasks")
print("Queue size: " .. stats.size)
print("Processing: " .. stats.processing)
```
### mq.awaitEmptyQueue(queue)
Waits for a queue to become empty.
Example:
```lua
mq.awaitEmptyQueue("tasks")
```
+7 -21
View File
@@ -4,30 +4,16 @@ references:
- client/space_lua/stdlib/net.ts
---
Network-related APIs.
The `net` namespace provides network and URI access.
## net.proxyFetch(url, options?)
Performs a HTTP call, proxied via the server (to avoid CORS issues, see [[HTTP API]]).
## Proxy request behavior
Options:
* `method`: GET, POST, PUT, DELETE (GET is default)
* `headers`: table with header -> value mappings
* `body`: either a string or table (which will be JSON stringified)
`net.proxyFetch` sends HTTP requests through the SilverBullet server to avoid browser CORS restrictions; see [[HTTP API]]. Its options table supports `method` (GET by default), `headers`, `body`, and `responseEncoding`. A table body is JSON-encoded automatically.
Returns:
* `ok`: boolean if the request went ok
* `status`: HTTP status code
* `headers`: HTTP headers
* `body`: for content types:
* `text/*`: string
* `application/json`: parsed JSON object
* anything else: UInt8Array
The response table contains `ok`, `status`, `headers`, and `body`. JSON responses are parsed into Lua-compatible values, text and XML responses become strings, other content becomes a byte buffer, and an empty body becomes `nil`.
## net.readURI(uri, options?)
Fetches the content of a [[URI]].
## URI services
Options:
* `encoding` force an encoding for the result, e.g. `{encoding = "text/markdown"}`
`net.readURI` and `net.writeURI` dispatch to the best service registered for the URI. Pass `{encoding = "text/markdown"}` to `net.readURI` when a service should force a particular result encoding.
## net.writeURI(uri, content)
Writes content to a specific [[URI|URI]].
${spacelua.renderApiDocumentation("net")}
+20 -57
View File
@@ -4,64 +4,27 @@ references:
- client/space_lua/stdlib/os.ts
---
API docs for Lua's `os` module.
The `os` namespace provides date, time, and clock functions.
## os.time(table?)
Returns the current time when called without arguments, or a timestamp for a specific date when given a table. The table can contain the following fields: year (required), month (required), day (required), hour (defaults to 12), min (defaults to 0), and sec (defaults to 0).
## Date formats
Example:
```lua
-- Get current timestamp
print(os.time()) -- prints: current Unix timestamp
`os.date` accepts ISO C `strftime`-style format strings. Prefix the format with `!` to use UTC, or use `*t` (and `!*t` for UTC) to return a table of date fields.
-- Get timestamp for specific date
local timestamp = os.time({
year = 2020,
month = 1,
day = 1
})
```
- `%Y`: full year
- `%y`: year without century
- `%m`: month from 01 through 12
- `%b` and `%B`: abbreviated and full month names
- `%d` and `%e`: zero-padded and unpadded day of month
- `%H` and `%I`: 24-hour and 12-hour hour
- `%M`: minute
- `%S`: second
- `%p`: AM or PM
- `%A` and `%a`: full and abbreviated weekday names
- `%w`: weekday from 0 through 6, with Sunday as 0
- `%U` and `%W`: week of year starting on Sunday or Monday
- `%V`: ISO 8601 week of year
- `%j`: day of year
- `%Z` and `%z`: time zone name and UTC offset
- `%%`: literal percent sign
## os.date(format?, timestamp?)
Returns a string or table containing date and time, formatted according to the given format string. If timestamp is not provided, formats the current time.
Format specifiers:
- `%Y`: Full year (e.g., "2024")
- `%y`: Year without century (e.g., "24")
- `%m`: Month (01-12)
- `%b`: Abbreviated month name (e.g., "Jan")
- `%B`: Full month name (e.g., "January")
- `%d`: Day of month (01-31)
- `%e`: Day of month (1-31)
- `%H`: Hour (00-23)
- `%I`: Hour (01-12)
- `%M`: Minute (00-59)
- `%S`: Second (00-59)
- `%p`: AM/PM
- `%A`: Full weekday name (e.g., "Sunday")
- `%a`: Abbreviated weekday name (e.g., "Sun")
- `%w`: Weekday (0-6, Sunday is 0)
- `%U`: Week of the year, starting with the first Sunday as the first day of week 01 (00-53)
- `%W`: Week of the year, starting with the first Monday as the first day of week 01 (00-53)
- `%V`: ISO 8601 week of the year (01-53) (see [Wikipedia](https://en.wikipedia.org/wiki/ISO_week_date))
- `%j`: Day of year (001-366)
- `%Z`: Time zone name
- `%z`: Time zone offset from UTC
- `%%`: Literal "%"
Example:
```lua
-- Format specific date
local date = os.date("%Y-%m-%d", os.time({
year = 2020,
month = 1,
day = 1
}))
print(date) -- prints: 2020-01-01
-- Current date in different formats
print(os.date("%Y-%m-%d")) -- prints: current date (e.g., "2024-03-14")
print(os.date("%B %d, %Y")) -- prints: month day, year (e.g., "March 14, 2024")
print(os.date("%I:%M %p")) -- prints: time in 12-hour format (e.g., "02:30 PM")
print(os.date("%A, %B %d, %Y")) -- prints: full date (e.g., "Thursday, March 14, 2024")
```
${spacelua.renderApiDocumentation("os")}
+7 -27
View File
@@ -5,21 +5,24 @@ references:
- client/plugos/syscalls/service_registry.ts
---
Exposes a simple service registry API leveraged by various parts of SilverBullet, see [[Service]].
The Service API exposes a simple service registry leveraged by various parts of SilverBullet. See [[Service]].
${spacelua.renderApiDocumentation("service")}
# Architecture
Services are built on top of [[Event|Events]]. When a service is defined, it registers two event listeners:
1. `discover:<<selector>>` — for service discovery
2. `service:<<guid>>` — for invocation
1. `discover:<<selector>>` for service discovery
2. `service:<<guid>>` for invocation
Discovery broadcasts on the event bus and collects all matches, sorted by priority. Invocation calls the specific service's `run` callback.
# Example
```space-lua
service.define {
selector = "greeter-service",
-- no priority set
match = {},
run = function(name)
return "Hello " .. name
@@ -30,7 +33,6 @@ service.define {
selector = "greeter-service",
match = function(name)
if name == "Pete" then
-- takes precendence with an exact match
return {priority=10}
else
return nil
@@ -43,25 +45,3 @@ service.define {
```
To invoke: ${service.invokeBestMatch("greeter-service", "Pete")} and ${service.invokeBestMatch("greeter-service", "Hank")}
# API
### service.define(spec)
Defines a service matching a selector.
Spec arguments:
* `selector`: service selector, can contain wildcards (e.g. `hello:*`)
* `match(data)`: callback (`data` argument), returns a match table if this service is a match or `nil` otherwise. A match table is service specific, but at least contains a `priority` key to set the service priority (used for sorting by `service.discover` and `service.invokeBestMatch`). Instead of a function can also simply be a match object directly.
* `run(data)`: callback to be invoked when the service is invoked
### service.discover(selector, data)
Discovers previously defined service matching a given selector.
Return value is a list of tables (can be empty) with keys:
* `id`: guid of the service (automatically generated)
* `priority`: priority of service match (list will already be pre-sorted based on this key if present)
### service.invoke(match, data)
Invokes a service match (as returned by [[#service.discover(selector, options)]]).
### service.invokeBestMatch(selector, data)
Performs a `discover` based on the selector, then immediately performs and `invoke` on the best match (based on priority).
+1 -23
View File
@@ -7,26 +7,4 @@ references:
The Shell API provides functions for running shell commands and interacting with processes.
### shell.run(cmd, args, stdin?)
Runs a shell command and returns its output.
Parameters:
- `cmd`: The command to run
- `args`: Array of arguments to pass to the command
- `stdin`: stdin string (optional)
Returns an object with:
- `stdout`: The standard output of the command
- `stderr`: The standard error of the command
- `code`: The exit code of the command
Example:
```lua
local result = shell.run("ls", {"-l"})
print("Output:", result.stdout)
print("Error:", result.stderr)
print("Exit code:", result.code)
local result = shell.run("cat", {}, "hello")
print("Output:", result.stdout) -- "hello"
```
${spacelua.renderApiDocumentation("shell")}
+1 -175
View File
@@ -8,178 +8,4 @@ references:
The Space API provides functions for interacting with pages, documents, and files in the space.
# Page Operations
## space.listPages()
Returns a list of all pages in the space.
Example:
```lua
local pages = space.listPages()
for page in each(pages) do
print(page.name)
end
```
## space.readPage(name)
Reads the content of a page.
Example:
```lua
local content = space.readPage("welcome")
print(content) -- prints the content of the "welcome" page
```
## space.readRef(ref)
Reads a reference and returns it as a string, works for:
* `page`: reads the entire page
* `page#header` reads the referenced header
* `page@pos` where `pos` points to an item or task: reads the item/task and its children
## space.getPageMeta(name)
Gets metadata for a specific page.
Example:
```lua
local meta = space.getPageMeta("welcome")
print(meta.name, meta.lastModified) -- prints page name and last modified date
```
## space.readPageWithMeta(name)
Combines readPage and getPageMeta in a single call, returning both in a table:
* `text`: the binary content
* `meta`: the meta data
## space.writePage(name, text)
Writes content to a page.
Example:
```lua
local meta = space.writePage("notes", "My new note content")
print("Page updated at: " .. meta.lastModified)
```
## space.deletePage(name)
Deletes a page from the space.
Example:
```lua
space.deletePage("old-notes")
```
## space.pageExists(name)
Checks if a page exists in the space.
Example:
```lua
if space.pageExists("Hello") then
print("Page exists!")
else
print("Page not found")
end
```
# Document Operations
## space.listDocuments()
Returns a list of all documents in the space.
Example:
```lua
local documents = space.listDocuments()
for doc in each(documents) do
print(doc.name, doc.size)
end
```
## space.readDocument(name)
Reads the content of a document.
Example:
```lua
local data = space.readDocument("image.png")
print("Document size: " .. #data .. " bytes")
```
## space.writeDocument(name, data)
Writes binary data to a document.
Example:
```lua
local binaryData = string.char(72, 69, 76, 76, 79) -- "HELLO" in binary
local meta = space.writeDocument("test.bin", binaryData)
print("Document saved with size: " .. meta.size)
```
## space.deleteDocument(name)
Deletes a document from the space.
Example:
```lua
space.deleteDocument("old-image.png")
```
# File Operations
## space.listFiles()
Returns a list of all files in the space.
Example:
```lua
local files = space.listFiles()
for _, file in ipairs(files) do
print(file.name, file.size)
end
```
## space.getFileMeta(name)
Gets metadata for a specific file.
Example:
```lua
local meta = space.getFileMeta("document.txt")
print(meta.name, meta.modified, meta.size)
```
## space.readFile(name)
Reads the content of a file.
Example:
```lua
local content = space.readFile("document.txt")
print("File size: " .. #content .. " bytes")
```
## space.readFileWithMeta(name)
Combines readFile and getFileMeta in a single call, returning both in a table:
* `data`: the binary content
* `meta`: the meta data
## space.writeFile(name, data)
Writes binary data to a file.
Example:
```lua
local text = "Hello, World!"
local meta = space.writeFile("greeting.txt", text)
print("File written with size: " .. meta.size)
```
## space.deleteFile(name)
Deletes a file from the space.
Example:
```lua
space.deleteFile("old-document.txt")
```
## space.fileExists(name)
Checks if a file exists in the space.
Example:
```lua
if space.fileExists("config.json") then
print("Config file exists!")
else
print("Config file not found")
end
${spacelua.renderApiDocumentation("space")}
+1 -78
View File
@@ -8,81 +8,4 @@ references:
The Space Lua API provides functions for working with Lua expressions and templates.
## spacelua.parseExpression(luaExpression)
Parses a lua expression and returns the parsed expression as an AST.
Example:
```lua
local parsedExpression = spacelua.parseExpression("1 + 1")
```
## spacelua.parseBlock(code)
Parses a Lua chunk (a block of statements) and returns the parsed block as an AST.
Example:
```lua
local parsedBlock = spacelua.parseBlock("local x = 1\nreturn x + 2")
```
## spacelua.prettyPrintExpression(parsedExpr, options?)
Pretty-prints a parsed Lua expression AST back to formatted Lua source.
The optional `options` table accepts:
* `indentWidth` (number, default `2`): number of spaces per indentation level.
* `quote` (`"double"` or `"single"`, default `"double"`): quote style for strings.
* `trailingComma` (boolean, default `true`): whether multi-line tables get a trailing comma.
> **note** Comments
> The parser does not retain comments, so pretty-printing a parsed AST does not preserve any comments from the original source.
Example:
```lua
local parsedExpr = spacelua.parseExpression("{a=1,b=2}")
print(spacelua.prettyPrintExpression(parsedExpr))
-- prints:
-- {
-- a = 1,
-- b = 2,
-- }
```
## spacelua.prettyPrintBlock(parsedBlock, options?)
Pretty-prints a parsed Lua block AST back to formatted Lua source. Accepts the same `options` table as [[#spacelua.prettyPrintExpression(parsedExpr, options?)]].
Reformatting a chunk of Lua source is a parse followed by a pretty-print:
```lua
local formatted = spacelua.prettyPrintBlock(spacelua.parseBlock("if a then return 1 end"))
print(formatted)
-- prints:
-- if a then
-- return 1
-- end
```
## spacelua.evalExpression(parsedExpr, envAugmentation?)
Evaluates a parsed Lua expression and returns the result. Optionally accepts an environment table to augment the global environment.
Example:
```lua
local parsedExpr = spacelua.parseExpression("x + y")
local result = spacelua.evalExpression(parsedExpr, {x = 1, y = 2})
print(result) -- prints: 3
```
## spacelua.interpolate(template, envAugmentation?)
Interpolates a string with lua expressions and returns the result. Expressions are wrapped in ${...} syntax. Optionally accepts an environment table to augment the global environment.
Example:
```lua
local greeting = spacelua.interpolate("Hello ${name}!", {name="Pete"})
print(greeting) -- prints: Hello Pete!
```
## spacelua.baseUrl()
Returns your SilverBullet instance's base URL, or `nil` when run on the server.
Example:
```lua
local url = spacelua.baseUrl()
print(url) -- prints something like: https://example.com
```
${spacelua.renderApiDocumentation("spacelua")}
+16 -240
View File
@@ -5,259 +5,35 @@ references:
- client/space_lua/stdlib/string_pack.ts
---
API docs for Space Lua's `string` module.
The `string` module contains Lua string operations and Space Lua extensions.
> **note** Note
> Since string values set `string` as their meta table, these APIs can also be called as method calls on strings directly. For instance: `someString:startsWith("h")` is equivalent to `string.startsWith(someString, "h")`.
> Since string values use `string` as their metatable, these APIs can also be called as methods. For example, `someString:startsWith("h")` is equivalent to `string.startsWith(someString, "h")`.
# Lua standard library
## Lua pattern matching
## Lua Pattern Matching
Lua patterns are not regular expressions. Space Lua makes a good effort at translating Lua patterns to regex to run in a Javascript environment, but there are two main differences:
Lua patterns are not regular expressions. Space Lua translates Lua patterns to JavaScript regular expressions and has a few compatibility differences:
1. Magic characters `^$()%.[]*+-?` must be escaped to represent their character. Standard Lua patterns do not require escaping magic characters when they are not contextually magic (e.g. `%d--` is a valid Lua pattern where the second hyphen is not magic). Space Lua may have unexpected results when expecting an un-escaped magic character to behave like a character.
2. In Space Lua, the repetition magic characters (`?`, `*`, `+`, and `-`) will apply to captures in patterns. They do not in standard Lua.
1. Magic characters `^$()%.[]*+-?` must be escaped to represent literal characters. Standard Lua does not require escaping a magic character when it is not contextually magic, so patterns such as `%d--` can behave differently in Space Lua.
2. Space Lua allows repetition characters (`?`, `*`, `+`, and `-`) to apply to captures; standard Lua does not.
3. The *n*th captured string (`%n`), balanced match (`%bxy`), and frontier pattern (`%f[set]`) forms from the [Lua 5.4 pattern manual](https://www.lua.org/manual/5.4/manual.html#6.4.1) may not be supported.
Additionally, the patterns for the *n*th captured string (`%*n*`), balanced match (`%b*xy*`), and frontier pattern (`%f[set]`) in [Lua](https://www.lua.org/manual/5.4/manual.html#6.4.1) will likely not be supported.
The `string.matchRegex` and `string.matchRegexAll` extensions use JavaScript regular expressions instead of Lua patterns.
As noted below, the operations `string.matchRegex` and `string.matchRegexAll`
leverage regex in Javascript--not Space Lua patterns.
Here are some valid Lua patterns with different matches (or outright errors) in Space Lua:
Examples of patterns that differ:
```lua
print(string.match("1234", "(%d)+"))
-- prints "4" in Space Lua (last match of the captures)
-- prints "nil" in Lua (repetition magic does not work on captures)
-- Space Lua prints "4" because repetition applies to the capture.
-- Standard Lua returns nil.
print(string.match("*", "*"))
-- invalid regex in Space Lua ("*" is not escaped)
-- prints "*" in Lua
-- Space Lua reports an invalid regular expression.
-- Standard Lua prints "*".
print(string.match("2024-03-14", "%d+-(%d+)-%d+"))
-- invalid regex in Space Lua (the "-"s are not escaped")
-- prints "03" in Lua
-- Space Lua reports an invalid regular expression because the hyphens are not escaped.
-- Standard Lua prints "03".
```
## String Operations
### string.byte(s, i?, j?)
Returns the numeric codes of characters in string `s` from position `i` to `j`. If `j` is not provided, defaults to `i`.
Example:
```lua
print(string.byte("Hello", 1)) -- prints: 72 (ASCII code for 'H')
```
### string.char(...)
Returns a string from given ASCII codes.
Example:
```lua
print(string.char(72)) -- prints: H
```
### string.find(s, pattern, init?, plain?)
Looks for the first match of `pattern` in string `s`. Returns start and end indices of match.
Example:
```lua
local start, end_ = string.find("Hello", "l")
print(start) -- prints: 3 (first 'l' position)
```
### string.format(format, ...)
Returns a formatted string using C-style format specifiers.
Example:
```lua
print(string.format("Name: %s, Age: %d", "John", 30)) -- prints: Name: John, Age: 30
print(string.format("Pi: %.2f", 3.14159)) -- prints: Pi: 3.14
```
### string.gsub(s, pattern, repl, n?)
Returns a copy of `s` in which all (or the first `n`) occurrences of `pattern` have been replaced by `repl`.
Example:
```lua
-- Simple string replacement
local result, count = string.gsub("hello world", "hello", "hi")
print(result, count) -- prints: hi world 1
-- Multiple replacements with limit
result = string.gsub("hello hello hello", "hello", "hi", 2)
print(result) -- prints: hi hi hello
-- Function replacement
result = string.gsub("hello world", "(h)ello", function(h)
return string.upper(h) .. "i"
end)
print(result) -- prints: Hi world
-- Pattern with magic characters
result = string.gsub("hello.world", "%.", "-")
print(result) -- prints: hello-world
```
### string.match(s, pattern, init?)
Returns the captures from the first match of `pattern` in string `s`.
Example:
```lua
-- Basic pattern matching
print(string.match("hello", "h")) -- prints: h
-- Multiple captures
local year, month, day = string.match("2024-03-14", "(%d+)%-(%d+)%-(%d+)")
print(year, month, day) -- prints: 2024 03 14
-- With init position
print(string.match("hello world", "(world)", 7)) -- prints: world
-- Pattern characters
print(string.match("123", "%d+")) -- prints: 123
print(string.match("abc123", "%a+")) -- prints: abc
print(string.match(" abc", "%s+")) -- prints: " "
```
### string.gmatch(s, pattern)
Returns an iterator function that returns successive captures from pattern matches in string `s`.
Example:
```lua
local words = {}
for word in string.gmatch("hello world lua", "%w+") do
table.insert(words, word)
end
print(words[1], words[2], words[3]) -- prints: hello world lua
```
### string.len(s)
Returns the length of string `s`.
Example:
```lua
print(string.len("Hello")) -- prints: 5
```
### string.lower(s)
Returns a copy of `s` with all characters converted to lowercase.
Example:
```lua
print(string.lower("Hello")) -- prints: hello
```
### string.upper(s)
Returns a copy of `s` with all characters converted to uppercase.
Example:
```lua
print(string.upper("Hello")) -- prints: HELLO
```
### string.rep(s, n, sep?)
Returns a string that is the concatenation of `n` copies of string `s`.
Example:
```lua
print(string.rep("Hello", 3)) -- prints: HelloHelloHello
```
### string.reverse(s)
Returns a string with the characters of `s` in reverse order.
Example:
```lua
print(string.reverse("hello")) -- prints: olleh
print(string.reverse("")) -- prints: "" (empty string)
```
### string.sub(s, i, j?)
Returns the substring of `s` from position `i` to `j`.
Example:
```lua
print(string.sub("Hello", 2, 4)) -- prints: ell
```
### string.split(s, sep)
Splits string `s` using separator `sep` and returns a table of substrings.
Example:
```lua
local parts = string.split("a,b,c", ",")
for i, part in ipairs(parts) do
print(part)
end
-- Output:
-- a
-- b
-- c
```
# Non-standard Extensions
## JavaScript inspired
### string.startsWith(s, prefix)
Returns true if string `s` starts with `prefix`.
Example:
```lua
print(string.startsWith("hello world", "hello")) -- prints: true
print(string.startsWith("hello world", "world")) -- prints: false
```
### string.endsWith(s, suffix)
Returns true if string `s` ends with `suffix`.
Example:
```lua
print(string.endsWith("hello world", "world")) -- prints: true
print(string.endsWith("hello world", "hello")) -- prints: false
```
### string.trim(s)
Returns a copy of string `s` with whitespace removed from both ends.
Example:
```lua
print(string.trim(" hello ")) -- prints: hello
```
### string.trimStart(s)
Returns a copy of string `s` with whitespace removed from the beginning.
Example:
```lua
print(string.trimStart(" hello ")) -- prints: hello
```
### string.trimEnd(s)
Returns a copy of string `s` with whitespace removed from the end.
Example:
```lua
print(string.trimEnd(" hello ")) -- prints: hello
```
### string.matchRegex(s, pattern)
Matches string `s` against a JavaScript regular expression pattern and returns the result. This uses JavaScript's native regex capabilities rather than Lua patterns.
Example:
```lua
local match = string.matchRegex("hello123", "([a-z]+)([0-9]+)")
print(match[1], match[2], match[3]) -- prints: hello123 hello 123
```
### string.matchRegexAll(s, pattern)
Returns an iterator that finds all matches of a JavaScript regular expression pattern in string `s`.
Example:
```lua
for match in string.matchRegexAll("a1b2c3", "([a-z])([0-9])") do
print(match[1], match[2], match[3]) -- prints each full match and its capture groups
end
-- Output:
-- a1 a 1
-- b2 b 2
-- c3 c 3
```
${spacelua.renderApiDocumentation("string")}
+1 -40
View File
@@ -8,43 +8,4 @@ references:
The Sync API provides functions for interacting with the sync engine when the client runs in Sync mode.
## Sync Operations
### sync.isSyncing()
Checks if a sync is currently in progress.
Example:
```lua
if sync.isSyncing() then
print("Sync in progress...")
end
```
### sync.hasInitialSyncCompleted()
Checks if an initial sync has completed.
Example:
```lua
if sync.hasInitialSyncCompleted() then
print("Initial sync completed")
else
print("Waiting for initial sync...")
end
```
### sync.performFileSync(path)
Immediately synchronizes a file with the server. Returns once the synchronization has completed.
Example:
```lua
sync.performFileSync("notes/important.md")
```
### sync.performSpaceSync()
Immediately triggers a full space sync. Returns `-1` if a sync was already ongoing, or the number of sync operations performed.
Example:
```lua
local changes = sync.scheduleSpaceSync()
print("Number of changes synced: " .. changes)
```
${spacelua.renderApiDocumentation("sync")}
+1 -99
View File
@@ -8,102 +8,4 @@ references:
The System API provides system-level functions for interacting with the SilverBullet environment.
## Function Operations
### system.invokeFunction(name, ...)
Invokes a plug function by name.
Example:
```lua
-- Invoke a function from a plug
system.invokeFunction("myplug.processData", "input", 123)
```
## System Information
### system.listCommands()
Lists all available commands.
Example:
```lua
local commands = system.listCommands()
for name, def in pairs(commands) do
print(name .. ": " .. def.description)
end
```
### system.listSyscalls()
Lists all available syscalls.
Example:
```lua
local syscalls = system.listSyscalls()
for _, syscall in ipairs(syscalls) do
print(syscall.name)
end
```
### system.getMode()
Returns the current mode of the system ("ro" or "rw").
Example:
```lua
local mode = system.getMode()
print("System mode: " .. mode)
```
### system.getURLPrefix()
Returns the prefix set by [[Install/Configuration|SB_URL_PREFIX]] or "/" if the variable isn't set
Example:
```lua
local prefix = system.getURLPrefix()
print("Prefix: " .. prefix)
```
### system.getVersion()
Returns the SilverBullet version.
Example:
```lua
local version = system.getVersion()
print("SilverBullet version: " .. version)
```
## Configuration
### system.reloadConfig()
Triggers an explicit reload of the configuration.
Example:
```lua
system.reloadConfig()
print("Configuration reloaded")
```
### system.reloadPlugs()
Triggers a reload of all plugs.
Example:
```lua
system.reloadPlugs()
print("All plugs reloaded")
```
### system.reboot()
Makes edited-on-disk state live and resolves only once the client is ready again. Useful for scripts, the `sb` CLI, and external tooling that change space files on disk and need a single "reboot to ready" call.
It mirrors the **System: Reload** command: it saves the currently-open editor buffer first, then flushes any latent on-disk changes into the index queue (via snapshot detection — not a full reindex), waits for indexing to finish, and finally re-applies configuration, scripts, and styles. Because the buffer is saved first, a raw on-disk edit to the *currently-open* page can be overwritten by the in-memory buffer; edit the open page through the editor (or navigate away) rather than on disk if that matters.
### system.wipeClient(logout?)
Completely wipes the client state, including cached files, service worker and databases.
Parameters:
- `logout`: Optional boolean to also log out the user
Example:
```lua
system.wipeClient(true) -- Wipe client and log out
print("Client state has been reset")
```
${spacelua.renderApiDocumentation("system")}
+2 -126
View File
@@ -4,130 +4,6 @@ references:
- client/space_lua/stdlib/table.ts
---
These are Lua functions defined in the `table` namespace.
The `table` namespace contains the Lua table library and Space Lua collection helpers.
# Lua standard library
## table.concat(table, sep?, i?, j?)
Concatenates the elements of a table into a string using a separator.
Example:
```lua
local fruits = {"apple", "banana", "orange"}
print(table.concat(fruits, ", ")) -- prints: apple, banana, orange
print(table.concat(fruits, "", 1, 2)) -- prints: applebanana
```
## table.insert(table, pos, value)
## table.insert(table, value)
Inserts a value into a table at the specified position, shifting elements up. If position is not provided, appends the value at the end of the table.
Example:
```lua
local fruits = {"apple", "orange"}
table.insert(fruits, "banana") -- appends at end
print(table.concat(fruits, ", ")) -- prints: apple, orange, banana
table.insert(fruits, 2, "grape") -- inserts at position 2
print(table.concat(fruits, ", ")) -- prints: apple, grape, orange, banana
```
## table.remove(table, pos?)
Removes an element from a table at the specified position, shifting elements down. If position is not provided, removes the last element.
Example:
```lua
local fruits = {"apple", "grape", "orange", "banana"}
table.remove(fruits, 2) -- removes "grape"
print(table.concat(fruits, ", ")) -- prints: apple, orange, banana
table.remove(fruits) -- removes last element
print(table.concat(fruits, ", ")) -- prints: apple, orange
```
## table.sort(table, comp?)
Sorts a table in-place using the optional comparison function. Without a comparison function, sorts in ascending order.
Example:
```lua
local numbers = {3, 1, 4, 1, 5, 9}
table.sort(numbers) -- ascending order
print(table.concat(numbers, ", ")) -- prints: 1, 1, 3, 4, 5, 9
-- Custom comparison (descending order)
table.sort(numbers, function(a, b) return a > b end)
print(table.concat(numbers, ", ")) -- prints: 9, 5, 4, 3, 1, 1
```
## table.pack(...)
Creates a new table with the given arguments. The resulting table has all arguments stored at integer keys starting with 1, and a field "n" with the total number of arguments.
Example:
```lua
local args = table.pack("apple", "banana", "orange")
print(args[1], args[2], args[3]) -- prints: apple banana orange
print(args.n) -- prints: 3
```
## table.unpack(table, i?, j?)
Returns all elements from the table as separate values. The optional `i` and `j` parameters specify the range of elements to return (defaults to 1 and the table length).
Example:
```lua
local fruits = {"apple", "banana", "orange"}
local a, b, c = table.unpack(fruits)
print(a, b, c) -- prints: apple banana orange
-- With range specification
local x, y = table.unpack(fruits, 2, 3)
print(x, y) -- prints: banana orange
```
# Non-standard APIs
## table.keys(table)
Returns an array containing all the keys in the table.
Example:
```lua
local person = {name = "John", age = 30, city = "New York"}
local keys = table.keys(person)
print(table.concat(keys, ", ")) -- prints: name, age, city
```
## table.includes(table, value)
Checks if a list-table contains a specific value.
Example:
```lua
local fruits = {"apple", "banana", "orange"}
print(table.includes(fruits, "banana")) -- prints: true
print(table.includes(fruits, "grape")) -- prints: false
```
## table.find(table, criteriaFn, fromIndex?)
Finds an element in a table that matches a criteria function. Returns a Lua multi value of index and first element or nil if no element is found.
Example:
```lua
local numbers = {1, 2, 3, 4, 5}
local _, firstEven = table.find(numbers, function(n) return n % 2 == 0 end)
print(firstEven) -- prints: 2
-- With fromIndex parameter
local _, firstEvenAfter3 = table.find(numbers, function(n) return n % 2 == 0 end, 3)
print(firstEvenAfter3) -- prints: 4
-- No match case
local result = table.find(numbers, function(n) return n > 10 end)
print(result) -- prints: nil
```
## table.select(table, keys...)
Returns a new table from an old one, only with selected keys.
Example:
${query[[
from p = index.pages()
limit 3
select table.select(p, "name", "lastModified")
]]}
${spacelua.renderApiDocumentation("table")}
+1 -32
View File
@@ -8,35 +8,4 @@ references:
The YAML API provides functions for parsing and stringifying YAML content.
### yaml.parse(text)
Parses a YAML string into a Lua table.
Example:
```lua
local text = [[
name: John
age: 30
hobbies:
- reading
- hiking
]]
local data = yaml.parse(text)
print(data.name) -- prints: John
print(data.hobbies[1]) -- prints: reading
```
### yaml.stringify(obj)
Converts a Lua table into a YAML string.
Example:
```lua
local data = {
name = "John",
age = 30,
hobbies = {"reading", "hiking"}
}
local yamlText = yaml.stringify(data)
print(yamlText)
```
${spacelua.renderApiDocumentation("yaml")}