Lua API docs

pull/1212/head^2
Zef Hemel 2025-01-16 20:05:13 +01:00
parent 34e50ae74d
commit 8b2e76ee51
6 changed files with 552 additions and 3 deletions

View File

@ -123,6 +123,7 @@ export const builtinLanguages: Record<string, Language> = {
parser: highlightingQueryParser,
}),
"space-lua": luaLanguage,
"lua": luaLanguage,
"template": extendedMarkdownLanguage,
"expression": LRLanguage.define({
name: "expression",

View File

@ -4,25 +4,202 @@ These are Lua functions defined in the global namespace:
## print(...)
Prints to your log (browser or server log).
## assert(expr)
Asserts `expr` to be true otherwise raises an [[#error]]
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
```
## 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
```
## 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: `error("FAIL")`
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"
```
# Space Lua specific
## tag(name)

75
website/API/js.md Normal file
View File

@ -0,0 +1,75 @@
API docs for Space Lua's `js` module, which provides JavaScript interoperability.
## js.import(url)
Imports a JavaScript module from a URL. Returns the imported module.
Example:
```lua
-- Import lodash library
local lodash = js.import("https://esm.sh/lodash@4.17.21")
local result = lodash.chunk({1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, 3)
-- Import moment.js for date handling
local moment = js.import("https://esm.sh/moment@2.30.1")
local day = moment("1995-12-25")
print(day.format("DD-MM-YYYY")) -- prints: 25-12-1995
```
## js.new(constructor, ...)
Creates a new instance of a JavaScript class. Takes a constructor function and its arguments.
Example:
```lua
local Date = js.import("https://esm.sh/date-fns")
local date = js.new(Date, "2024-03-14")
```
## js.stringify(value)
Converts a Lua value to a JSON string representation.
Example:
```lua
local data = {1, 2, 3}
print(js.stringify(data)) -- prints: [1,2,3]
local nested = lodash.chunk({1, 2, 3, 4, 5, 6}, 2)
print(js.stringify(nested)) -- 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.each_iterable(iterable)
Creates an iterator for JavaScript async iterables.
Example:
```lua
local async_iterator = js.each_iterable(some_js_async_iterable)
for value in async_iterator do
print(value)
end
```

58
website/API/os.md Normal file
View File

@ -0,0 +1,58 @@
API docs for Lua's `os` module.
## 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).
Example:
```lua
-- Get current timestamp
print(os.time()) -- prints: current Unix timestamp
-- Get timestamp for specific date
local timestamp = os.time({
year = 2020,
month = 1,
day = 1
})
```
## 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)
- `%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")
```

166
website/API/string.md Normal file
View File

@ -0,0 +1,166 @@
API docs for Lua's `string` module.
## 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.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 day, month, year = string.match("2024-03-14", "(%d+)-(%d+)-(%d+)")
print(day, month, year) -- 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
## 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
```

72
website/API/table.md Normal file
View File

@ -0,0 +1,72 @@
These are Lua functions defined in the `table` namespace:
## 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.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
```