summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
author最萌小汐 <sumneko@hotmail.com>2022-02-23 17:56:26 +0800
committer最萌小汐 <sumneko@hotmail.com>2022-02-23 17:56:26 +0800
commit3de3402c82c4ea46f69d0a96bea7faf1ad68ea06 (patch)
tree32827d7d1e7c0b1ecd5386cd638498176d9aa866
parentf8e2955268708728a1f83743d0b2000d2e089539 (diff)
parentb37ebceffe695defd7e7976e653ce127618614c0 (diff)
downloadlua-language-server-3de3402c82c4ea46f69d0a96bea7faf1ad68ea06.zip
Merge commit 'b37ebceffe695defd7e7976e653ce127618614c0' into 3.0
-rw-r--r--.vscode/settings.json1
m---------3rd/EmmyLuaCodeStyle0
m---------3rd/bee.lua0
m---------3rd/lovr-api0
m---------3rd/luamake0
-rw-r--r--changelog.md8
-rw-r--r--locale/en-us/meta.lua816
-rw-r--r--locale/en-us/script.lua723
-rw-r--r--locale/en-us/setting.lua266
-rw-r--r--locale/pt-br/meta.lua819
-rw-r--r--locale/pt-br/script.lua711
-rw-r--r--locale/zh-cn/meta.lua816
-rw-r--r--locale/zh-cn/script.lua723
-rw-r--r--locale/zh-cn/setting.lua317
-rw-r--r--meta/3rd/love2d/library/love.graphics.lua12
-rw-r--r--meta/3rd/love2d/library/love.lua1
-rw-r--r--meta/3rd/lovr/library/callback.lua116
-rw-r--r--meta/3rd/lovr/library/lovr.audio.lua357
-rw-r--r--meta/3rd/lovr/library/lovr.data.lua226
-rw-r--r--meta/3rd/lovr/library/lovr.event.lua52
-rw-r--r--meta/3rd/lovr/library/lovr.filesystem.lua136
-rw-r--r--meta/3rd/lovr/library/lovr.graphics.lua1417
-rw-r--r--meta/3rd/lovr/library/lovr.headset.lua365
-rw-r--r--meta/3rd/lovr/library/lovr.lua22
-rw-r--r--meta/3rd/lovr/library/lovr.math.lua341
-rw-r--r--meta/3rd/lovr/library/lovr.physics.lua506
-rw-r--r--meta/3rd/lovr/library/lovr.system.lua8
-rw-r--r--meta/3rd/lovr/library/lovr.thread.lua72
-rw-r--r--meta/3rd/lovr/library/lovr.timer.lua26
-rw-r--r--script/client.lua6
-rw-r--r--script/config/config.lua7
-rw-r--r--script/core/formatting.lua8
-rw-r--r--script/core/rangeformatting.lua4
-rw-r--r--script/global.d.lua6
-rw-r--r--script/parser/guide.lua18
-rw-r--r--script/provider/capability.lua91
-rw-r--r--script/provider/formatting.lua14
-rw-r--r--script/provider/provider.lua117
-rw-r--r--script/service/telemetry.lua29
-rw-r--r--script/vm/getDocs.lua3
-rw-r--r--script/workspace/require-path.lua3
-rw-r--r--script/workspace/workspace.lua1
-rw-r--r--tools/love-api.lua33
-rw-r--r--tools/lovr-api.lua33
44 files changed, 7067 insertions, 2163 deletions
diff --git a/.vscode/settings.json b/.vscode/settings.json
index f8ca82c5..0260f483 100644
--- a/.vscode/settings.json
+++ b/.vscode/settings.json
@@ -1,6 +1,7 @@
// Just some comment
{
"Lua.misc.parameters": [
+ "--preview",
"--develop=true",
"--dbgport=11413",
]
diff --git a/3rd/EmmyLuaCodeStyle b/3rd/EmmyLuaCodeStyle
-Subproject ddc8c39b247f5ec1eb82398c9c73d5bd9c76bc7
+Subproject da71a27a82d36c4c8b031f9d53ca6935894970b
diff --git a/3rd/bee.lua b/3rd/bee.lua
-Subproject 226b4f55938dff7e3424437aac77e1b0932d98c
+Subproject 55c9c6bfd6ae4a576cd8777e232d7be48253b94
diff --git a/3rd/lovr-api b/3rd/lovr-api
-Subproject 460b954143b298a580ef3f7bffff2fc621545f3
+Subproject 8548de845c91dfd8639d47018b7d421f857322e
diff --git a/3rd/luamake b/3rd/luamake
-Subproject 843262572a2765ebe187573e32c4f8f22952c2c
+Subproject 909a3bf9770c61efc8a3050402ecbfa4daf24dd
diff --git a/changelog.md b/changelog.md
index f689713c..9d4162b6 100644
--- a/changelog.md
+++ b/changelog.md
@@ -1,6 +1,14 @@
# changelog
+## 2.6.6
+`2022-2-21`
+* `NEW` formatter preview, use `--preview` to enable this feature, [read more](https://github.com/sumneko/lua-language-server/issues/960)
+* `FIX` [#958](https://github.com/sumneko/lua-language-server/issues/958)
+* `FIX` runtime errors
+
## 2.6.5
+`2022-2-17`
+* `FIX` telemetry is not disabled by default (since 2.6.0)
* `FIX` [#934](https://github.com/sumneko/lua-language-server/issues/934)
* `FIX` [#952](https://github.com/sumneko/lua-language-server/issues/952)
diff --git a/locale/en-us/meta.lua b/locale/en-us/meta.lua
index 739781ca..858cde13 100644
--- a/locale/en-us/meta.lua
+++ b/locale/en-us/meta.lua
@@ -1,55 +1,84 @@
---@diagnostic disable: undefined-global, lowercase-global
-- basic
-arg = 'Command-line arguments of Lua Standalone.'
-assert = 'Raises an error if the value of its argument v is false (i.e., `nil` or `false`); otherwise, returns all its arguments. In case of error, `message` is the error object; when absent, it defaults to `"assertion failed!"`'
-cgopt.collect = 'Performs a full garbage-collection cycle.'
-cgopt.stop = 'Stops automatic execution.'
-cgopt.restart = 'Restarts automatic execution.'
-cgopt.count = 'Returns the total memory in Kbytes.'
-cgopt.step = 'Performs a garbage-collection step.'
-cgopt.setpause = 'Set `pause`.'
-cgopt.setstepmul = 'Set `step multiplier`.'
-cgopt.incremental = 'Change the collector mode to incremental.'
-cgopt.generational = 'Change the collector mode to generational.'
-cgopt.isrunning = 'Returns whether the collector is running.'
-collectgarbage = 'This function is a generic interface to the garbage collector. It performs different functions according to its first argument, `opt`.'
-dofile = 'Opens the named file and executes its content as a Lua chunk. When called without arguments, `dofile` executes the content of the standard input (`stdin`). Returns all values returned by the chunk. In case of errors, `dofile` propagates the error to its caller. (That is, `dofile` does not run in protected mode.)'
-error = [[
+arg =
+'Command-line arguments of Lua Standalone.'
+assert =
+'Raises an error if the value of its argument v is false (i.e., `nil` or `false`); otherwise, returns all its arguments. In case of error, `message` is the error object; when absent, it defaults to `"assertion failed!"`'
+cgopt.collect =
+'Performs a full garbage-collection cycle.'
+cgopt.stop =
+'Stops automatic execution.'
+cgopt.restart =
+'Restarts automatic execution.'
+cgopt.count =
+'Returns the total memory in Kbytes.'
+cgopt.step =
+'Performs a garbage-collection step.'
+cgopt.setpause =
+'Set `pause`.'
+cgopt.setstepmul =
+'Set `step multiplier`.'
+cgopt.incremental =
+'Change the collector mode to incremental.'
+cgopt.generational =
+'Change the collector mode to generational.'
+cgopt.isrunning =
+'Returns whether the collector is running.'
+collectgarbage =
+'This function is a generic interface to the garbage collector. It performs different functions according to its first argument, `opt`.'
+dofile =
+'Opens the named file and executes its content as a Lua chunk. When called without arguments, `dofile` executes the content of the standard input (`stdin`). Returns all values returned by the chunk. In case of errors, `dofile` propagates the error to its caller. (That is, `dofile` does not run in protected mode.)'
+error =
+[[
Terminates the last protected function called and returns message as the error object.
Usually, `error` adds some information about the error position at the beginning of the message, if the message is a string.
]]
-_G = 'A global variable (not a function) that holds the global environment (see §2.2). Lua itself does not use this variable; changing its value does not affect any environment, nor vice versa.'
-getfenv = 'Returns the current environment in use by the function. `f` can be a Lua function or a number that specifies the function at that stack level.'
-getmetatable = 'If object does not have a metatable, returns nil. Otherwise, if the object\'s metatable has a __metatable field, returns the associated value. Otherwise, returns the metatable of the given object.'
-ipairs = [[
+_G =
+'A global variable (not a function) that holds the global environment (see §2.2). Lua itself does not use this variable; changing its value does not affect any environment, nor vice versa.'
+getfenv =
+'Returns the current environment in use by the function. `f` can be a Lua function or a number that specifies the function at that stack level.'
+getmetatable =
+'If object does not have a metatable, returns nil. Otherwise, if the object\'s metatable has a __metatable field, returns the associated value. Otherwise, returns the metatable of the given object.'
+ipairs =
+[[
Returns three values (an iterator function, the table `t`, and `0`) so that the construction
```lua
for i,v in ipairs(t) do body end
```
will iterate over the key–value pairs `(1,t[1]), (2,t[2]), ...`, up to the first absent index.
]]
-loadmode.b = 'Only binary chunks.'
-loadmode.t = 'Only text chunks.'
-loadmode.bt = 'Both binary and text.'
-load['<5.1'] = 'Loads a chunk using function `func` to get its pieces. Each call to `func` must return a string that concatenates with previous results.'
-load['>5.2'] = [[
+loadmode.b =
+'Only binary chunks.'
+loadmode.t =
+'Only text chunks.'
+loadmode.bt =
+'Both binary and text.'
+load['<5.1'] =
+'Loads a chunk using function `func` to get its pieces. Each call to `func` must return a string that concatenates with previous results.'
+load['>5.2'] =
+[[
Loads a chunk.
If `chunk` is a string, the chunk is this string. If `chunk` is a function, `load` calls it repeatedly to get the chunk pieces. Each call to `chunk` must return a string that concatenates with previous results. A return of an empty string, `nil`, or no value signals the end of the chunk.
]]
-loadfile = 'Loads a chunk from file `filename` or from the standard input, if no file name is given.'
-loadstring = 'Loads a chunk from the given string.'
-module = 'Creates a module.'
-next = [[
+loadfile =
+'Loads a chunk from file `filename` or from the standard input, if no file name is given.'
+loadstring =
+'Loads a chunk from the given string.'
+module =
+'Creates a module.'
+next =
+[[
Allows a program to traverse all fields of a table. Its first argument is a table and its second argument is an index in this table. A call to `next` returns the next index of the table and its associated value. When called with `nil` as its second argument, `next` returns an initial index and its associated value. When called with the last index, or with `nil` in an empty table, `next` returns `nil`. If the second argument is absent, then it is interpreted as `nil`. In particular, you can use `next(t)` to check whether a table is empty.
The order in which the indices are enumerated is not specified, *even for numeric indices*. (To traverse a table in numerical order, use a numerical `for`.)
The behavior of `next` is undefined if, during the traversal, you assign any value to a non-existent field in the table. You may however modify existing fields. In particular, you may set existing fields to nil.
]]
-pairs = [[
+pairs =
+[[
If `t` has a metamethod `__pairs`, calls it with t as argument and returns the first three results from the call.
Otherwise, returns three values: the $next function, the table `t`, and `nil`, so that the construction
@@ -60,160 +89,246 @@ will iterate over all key–value pairs of table `t`.
See function $next for the caveats of modifying the table during its traversal.
]]
-pcall = [[
+pcall =
+[[
Calls the function `f` with the given arguments in *protected mode*. This means that any error inside `f` is not propagated; instead, `pcall` catches the error and returns a status code. Its first result is the status code (a boolean), which is true if the call succeeds without errors. In such case, `pcall` also returns all results from the call, after this first result. In case of any error, `pcall` returns `false` plus the error object.
]]
-print = [[
+print =
+[[
Receives any number of arguments and prints their values to `stdout`, converting each argument to a string following the same rules of $tostring.
The function print is not intended for formatted output, but only as a quick way to show a value, for instance for debugging. For complete control over the output, use $string.format and $io.write.
]]
-rawequal = 'Checks whether v1 is equal to v2, without invoking the `__eq` metamethod.'
-rawget = 'Gets the real value of `table[index]`, without invoking the `__index` metamethod.'
-rawlen = 'Returns the length of the object `v`, without invoking the `__len` metamethod.'
-rawset = [[
+rawequal =
+'Checks whether v1 is equal to v2, without invoking the `__eq` metamethod.'
+rawget =
+'Gets the real value of `table[index]`, without invoking the `__index` metamethod.'
+rawlen =
+'Returns the length of the object `v`, without invoking the `__len` metamethod.'
+rawset =
+[[
Sets the real value of `table[index]` to `value`, without using the `__newindex` metavalue. `table` must be a table, `index` any value different from `nil` and `NaN`, and `value` any Lua value.
This function returns `table`.
]]
-select = 'If `index` is a number, returns all arguments after argument number `index`; a negative number indexes from the end (`-1` is the last argument). Otherwise, `index` must be the string `"#"`, and `select` returns the total number of extra arguments it received.'
-setfenv = 'Sets the environment to be used by the given function. '
-setmetatable = [[
+select =
+'If `index` is a number, returns all arguments after argument number `index`; a negative number indexes from the end (`-1` is the last argument). Otherwise, `index` must be the string `"#"`, and `select` returns the total number of extra arguments it received.'
+setfenv =
+'Sets the environment to be used by the given function. '
+setmetatable =
+[[
Sets the metatable for the given table. If `metatable` is `nil`, removes the metatable of the given table. If the original metatable has a `__metatable` field, raises an error.
This function returns `table`.
To change the metatable of other types from Lua code, you must use the debug library (§6.10).
]]
-tonumber = [[
+tonumber =
+[[
When called with no `base`, `tonumber` tries to convert its argument to a number. If the argument is already a number or a string convertible to a number, then `tonumber` returns this number; otherwise, it returns `fail`.
The conversion of strings can result in integers or floats, according to the lexical conventions of Lua (see §3.1). The string may have leading and trailing spaces and a sign.
]]
-tostring = [[
+tostring =
+[[
Receives a value of any type and converts it to a string in a human-readable format.
If the metatable of `v` has a `__tostring` field, then `tostring` calls the corresponding value with `v` as argument, and uses the result of the call as its result. Otherwise, if the metatable of `v` has a `__name` field with a string value, `tostring` may use that string in its final result.
For complete control of how numbers are converted, use $string.format.
]]
-type = [[
+type =
+[[
Returns the type of its only argument, coded as a string. The possible results of this function are `"nil"` (a string, not the value `nil`), `"number"`, `"string"`, `"boolean"`, `"table"`, `"function"`, `"thread"`, and `"userdata"`.
]]
-_VERSION = 'A global variable (not a function) that holds a string containing the running Lua version.'
-warn = 'Emits a warning with a message composed by the concatenation of all its arguments (which should be strings).'
-xpcall['=5.1'] = 'Calls function `f` with the given arguments in protected mode with a new message handler.'
-xpcall['>5.2'] = 'Calls function `f` with the given arguments in protected mode with a new message handler.'
-unpack = [[
+_VERSION =
+'A global variable (not a function) that holds a string containing the running Lua version.'
+warn =
+'Emits a warning with a message composed by the concatenation of all its arguments (which should be strings).'
+xpcall['=5.1'] =
+'Calls function `f` with the given arguments in protected mode with a new message handler.'
+xpcall['>5.2'] =
+'Calls function `f` with the given arguments in protected mode with a new message handler.'
+unpack =
+[[
Returns the elements from the given `list`. This function is equivalent to
```lua
return list[i], list[i+1], ···, list[j]
```
]]
-bit32 = ''
-bit32.arshift = [[
+bit32 =
+''
+bit32.arshift =
+[[
Returns the number `x` shifted `disp` bits to the right. Negative displacements shift to the left.
This shift operation is what is called arithmetic shift. Vacant bits on the left are filled with copies of the higher bit of `x`; vacant bits on the right are filled with zeros.
]]
-bit32.band = 'Returns the bitwise *and* of its operands.'
-bit32.bnot = [[
+bit32.band =
+'Returns the bitwise *and* of its operands.'
+bit32.bnot =
+[[
Returns the bitwise negation of `x`.
```lua
-assert(bit32.bnot(x) == (-1 - x) % 2^32)
+assert(bit32.bnot(x) ==
+(-1 - x) % 2^32)
```
]]
-bit32.bor = 'Returns the bitwise *or* of its operands.'
-bit32.btest = 'Returns a boolean signaling whether the bitwise *and* of its operands is different from zero.'
-bit32.bxor = 'Returns the bitwise *exclusive or* of its operands.'
-bit32.extract = 'Returns the unsigned number formed by the bits `field` to `field + width - 1` from `n`.'
-bit32.replace = 'Returns a copy of `n` with the bits `field` to `field + width - 1` replaced by the value `v` .'
-bit32.lrotate = 'Returns the number `x` rotated `disp` bits to the left. Negative displacements rotate to the right.'
-bit32.lshift = [[
+bit32.bor =
+'Returns the bitwise *or* of its operands.'
+bit32.btest =
+'Returns a boolean signaling whether the bitwise *and* of its operands is different from zero.'
+bit32.bxor =
+'Returns the bitwise *exclusive or* of its operands.'
+bit32.extract =
+'Returns the unsigned number formed by the bits `field` to `field + width - 1` from `n`.'
+bit32.replace =
+'Returns a copy of `n` with the bits `field` to `field + width - 1` replaced by the value `v` .'
+bit32.lrotate =
+'Returns the number `x` rotated `disp` bits to the left. Negative displacements rotate to the right.'
+bit32.lshift =
+[[
Returns the number `x` shifted `disp` bits to the left. Negative displacements shift to the right. In any direction, vacant bits are filled with zeros.
```lua
-assert(bit32.lshift(b, disp) == (b * 2^disp) % 2^32)
+assert(bit32.lshift(b, disp) ==
+(b * 2^disp) % 2^32)
```
]]
-bit32.rrotate = 'Returns the number `x` rotated `disp` bits to the right. Negative displacements rotate to the left.'
-bit32.rshift = [[
+bit32.rrotate =
+'Returns the number `x` rotated `disp` bits to the right. Negative displacements rotate to the left.'
+bit32.rshift =
+[[
Returns the number `x` shifted `disp` bits to the right. Negative displacements shift to the left. In any direction, vacant bits are filled with zeros.
```lua
-assert(bit32.rshift(b, disp) == math.floor(b % 2^32 / 2^disp))
+assert(bit32.rshift(b, disp) ==
+math.floor(b % 2^32 / 2^disp))
```
]]
-coroutine = ''
-coroutine.create = 'Creates a new coroutine, with body `f`. `f` must be a function. Returns this new coroutine, an object with type `"thread"`.'
-coroutine.isyieldable = 'Returns true when the running coroutine can yield.'
-coroutine.isyieldable['>5.4']= 'Returns true when the coroutine `co` can yield. The default for `co` is the running coroutine.'
-coroutine.close = 'Closes coroutine `co` , closing all its pending to-be-closed variables and putting the coroutine in a dead state.'
-coroutine.resume = 'Starts or continues the execution of coroutine `co`.'
-coroutine.running = 'Returns the running coroutine plus a boolean, true when the running coroutine is the main one.'
-coroutine.status = 'Returns the status of coroutine `co`.'
-coroutine.wrap = 'Creates a new coroutine, with body `f`; `f` must be a function. Returns a function that resumes the coroutine each time it is called.'
-coroutine.yield = 'Suspends the execution of the calling coroutine.'
-costatus.running = 'Is running.'
-costatus.suspended = 'Is suspended or not started.'
-costatus.normal = 'Is active but not running.'
-costatus.dead = 'Has finished or stopped with an error.'
+coroutine =
+''
+coroutine.create =
+'Creates a new coroutine, with body `f`. `f` must be a function. Returns this new coroutine, an object with type `"thread"`.'
+coroutine.isyieldable =
+'Returns true when the running coroutine can yield.'
+coroutine.isyieldable['>5.4']=
+'Returns true when the coroutine `co` can yield. The default for `co` is the running coroutine.'
+coroutine.close =
+'Closes coroutine `co` , closing all its pending to-be-closed variables and putting the coroutine in a dead state.'
+coroutine.resume =
+'Starts or continues the execution of coroutine `co`.'
+coroutine.running =
+'Returns the running coroutine plus a boolean, true when the running coroutine is the main one.'
+coroutine.status =
+'Returns the status of coroutine `co`.'
+coroutine.wrap =
+'Creates a new coroutine, with body `f`; `f` must be a function. Returns a function that resumes the coroutine each time it is called.'
+coroutine.yield =
+'Suspends the execution of the calling coroutine.'
+costatus.running =
+'Is running.'
+costatus.suspended =
+'Is suspended or not started.'
+costatus.normal =
+'Is active but not running.'
+costatus.dead =
+'Has finished or stopped with an error.'
-debug = ''
-debug.debug = 'Enters an interactive mode with the user, running each string that the user enters.'
-debug.getfenv = 'Returns the environment of object `o` .'
-debug.gethook = 'Returns the current hook settings of the thread.'
-debug.getinfo = 'Returns a table with information about a function.'
-debug.getlocal['<5.1'] = 'Returns the name and the value of the local variable with index `local` of the function at level `level` of the stack.'
-debug.getlocal['>5.2'] = 'Returns the name and the value of the local variable with index `local` of the function at level `f` of the stack.'
-debug.getmetatable = 'Returns the metatable of the given value.'
-debug.getregistry = 'Returns the registry table.'
-debug.getupvalue = 'Returns the name and the value of the upvalue with index `up` of the function.'
-debug.getuservalue['<5.3'] = 'Returns the Lua value associated to u.'
-debug.getuservalue['>5.4'] = [[
+debug =
+''
+debug.debug =
+'Enters an interactive mode with the user, running each string that the user enters.'
+debug.getfenv =
+'Returns the environment of object `o` .'
+debug.gethook =
+'Returns the current hook settings of the thread.'
+debug.getinfo =
+'Returns a table with information about a function.'
+debug.getlocal['<5.1'] =
+'Returns the name and the value of the local variable with index `local` of the function at level `level` of the stack.'
+debug.getlocal['>5.2'] =
+'Returns the name and the value of the local variable with index `local` of the function at level `f` of the stack.'
+debug.getmetatable =
+'Returns the metatable of the given value.'
+debug.getregistry =
+'Returns the registry table.'
+debug.getupvalue =
+'Returns the name and the value of the upvalue with index `up` of the function.'
+debug.getuservalue['<5.3'] =
+'Returns the Lua value associated to u.'
+debug.getuservalue['>5.4'] =
+[[
Returns the `n`-th user value associated
to the userdata `u` plus a boolean,
`false` if the userdata does not have that value.
]]
-debug.setcstacklimit = [[
+debug.setcstacklimit =
+[[
### **Deprecated in `Lua 5.4.2`**
Sets a new limit for the C stack. This limit controls how deeply nested calls can go in Lua, with the intent of avoiding a stack overflow.
In case of success, this function returns the old limit. In case of error, it returns `false`.
]]
-debug.setfenv = 'Sets the environment of the given `object` to the given `table` .'
-debug.sethook = 'Sets the given function as a hook.'
-debug.setlocal = 'Assigns the `value` to the local variable with index `local` of the function at `level` of the stack.'
-debug.setmetatable = 'Sets the metatable for the given value to the given table (which can be `nil`).'
-debug.setupvalue = 'Assigns the `value` to the upvalue with index `up` of the function.'
-debug.setuservalue['<5.3'] = 'Sets the given value as the Lua value associated to the given udata.'
-debug.setuservalue['>5.4'] = [[
+debug.setfenv =
+'Sets the environment of the given `object` to the given `table` .'
+debug.sethook =
+'Sets the given function as a hook.'
+debug.setlocal =
+'Assigns the `value` to the local variable with index `local` of the function at `level` of the stack.'
+debug.setmetatable =
+'Sets the metatable for the given value to the given table (which can be `nil`).'
+debug.setupvalue =
+'Assigns the `value` to the upvalue with index `up` of the function.'
+debug.setuservalue['<5.3'] =
+'Sets the given value as the Lua value associated to the given udata.'
+debug.setuservalue['>5.4'] =
+[[
Sets the given `value` as
the `n`-th user value associated to the given `udata`.
`udata` must be a full userdata.
]]
-debug.traceback = 'Returns a string with a traceback of the call stack. The optional message string is appended at the beginning of the traceback.'
-debug.upvalueid = 'Returns a unique identifier (as a light userdata) for the upvalue numbered `n` from the given function.'
-debug.upvaluejoin = 'Make the `n1`-th upvalue of the Lua closure `f1` refer to the `n2`-th upvalue of the Lua closure `f2`.'
-infowhat.n = '`name` and `namewhat`'
-infowhat.S = '`source`, `short_src`, `linedefined`, `lastlinedefined`, and `what`'
-infowhat.l = '`currentline`'
-infowhat.t = '`istailcall`'
-infowhat.u['<5.1'] = '`nups`'
-infowhat.u['>5.2'] = '`nups`, `nparams`, and `isvararg`'
-infowhat.f = '`func`'
-infowhat.r = '`ftransfer` and `ntransfer`'
-infowhat.L = '`activelines`'
-hookmask.c = 'Calls hook when Lua calls a function.'
-hookmask.r = 'Calls hook when Lua returns from a function.'
-hookmask.l = 'Calls hook when Lua enters a new line of code.'
+debug.traceback =
+'Returns a string with a traceback of the call stack. The optional message string is appended at the beginning of the traceback.'
+debug.upvalueid =
+'Returns a unique identifier (as a light userdata) for the upvalue numbered `n` from the given function.'
+debug.upvaluejoin =
+'Make the `n1`-th upvalue of the Lua closure `f1` refer to the `n2`-th upvalue of the Lua closure `f2`.'
+infowhat.n =
+'`name` and `namewhat`'
+infowhat.S =
+'`source`, `short_src`, `linedefined`, `lastlinedefined`, and `what`'
+infowhat.l =
+'`currentline`'
+infowhat.t =
+'`istailcall`'
+infowhat.u['<5.1'] =
+'`nups`'
+infowhat.u['>5.2'] =
+'`nups`, `nparams`, and `isvararg`'
+infowhat.f =
+'`func`'
+infowhat.r =
+'`ftransfer` and `ntransfer`'
+infowhat.L =
+'`activelines`'
+hookmask.c =
+'Calls hook when Lua calls a function.'
+hookmask.r =
+'Calls hook when Lua returns from a function.'
+hookmask.l =
+'Calls hook when Lua enters a new line of code.'
-file = ''
-file[':close'] = 'Close `file`.'
-file[':flush'] = 'Saves any written data to `file`.'
-file[':lines'] = [[
+file =
+''
+file[':close'] =
+'Close `file`.'
+file[':flush'] =
+'Saves any written data to `file`.'
+file[':lines'] =
+[[
------
```lua
for c in file:lines(...) do
@@ -221,29 +336,51 @@ for c in file:lines(...) do
end
```
]]
-file[':read'] = 'Reads the `file`, according to the given formats, which specify what to read.'
-file[':seek'] = 'Sets and gets the file position, measured from the beginning of the file.'
-file[':setvbuf'] = 'Sets the buffering mode for an output file.'
-file[':write'] = 'Writes the value of each of its arguments to `file`.'
-readmode.n = 'Reads a numeral and returns it as number.'
-readmode.a = 'Reads the whole file.'
-readmode.l = 'Reads the next line skipping the end of line.'
-readmode.L = 'Reads the next line keeping the end of line.'
-seekwhence.set = 'Base is beginning of the file.'
-seekwhence.cur = 'Base is current position.'
-seekwhence['.end'] = 'Base is end of file.'
-vbuf.no = 'Output operation appears immediately.'
-vbuf.full = 'Performed only when the buffer is full.'
-vbuf.line = 'Buffered until a newline is output.'
+file[':read'] =
+'Reads the `file`, according to the given formats, which specify what to read.'
+file[':seek'] =
+'Sets and gets the file position, measured from the beginning of the file.'
+file[':setvbuf'] =
+'Sets the buffering mode for an output file.'
+file[':write'] =
+'Writes the value of each of its arguments to `file`.'
+readmode.n =
+'Reads a numeral and returns it as number.'
+readmode.a =
+'Reads the whole file.'
+readmode.l =
+'Reads the next line skipping the end of line.'
+readmode.L =
+'Reads the next line keeping the end of line.'
+seekwhence.set =
+'Base is beginning of the file.'
+seekwhence.cur =
+'Base is current position.'
+seekwhence['.end'] =
+'Base is end of file.'
+vbuf.no =
+'Output operation appears immediately.'
+vbuf.full =
+'Performed only when the buffer is full.'
+vbuf.line =
+'Buffered until a newline is output.'
-io = ''
-io.stdin = 'standard input.'
-io.stdout = 'standard output.'
-io.stderr = 'standard error.'
-io.close = 'Close `file` or default output file.'
-io.flush = 'Saves any written data to default output file.'
-io.input = 'Sets `file` as the default input file.'
-io.lines = [[
+io =
+''
+io.stdin =
+'standard input.'
+io.stdout =
+'standard output.'
+io.stderr =
+'standard error.'
+io.close =
+'Close `file` or default output file.'
+io.flush =
+'Saves any written data to default output file.'
+io.input =
+'Sets `file` as the default input file.'
+io.lines =
+[[
------
```lua
for c in io.lines(filename, ...) do
@@ -251,161 +388,289 @@ for c in io.lines(filename, ...) do
end
```
]]
-io.open = 'Opens a file, in the mode specified in the string `mode`.'
-io.output = 'Sets `file` as the default output file.'
-io.popen = 'Starts program prog in a separated process.'
-io.read = 'Reads the `file`, according to the given formats, which specify what to read.'
-io.tmpfile = 'In case of success, returns a handle for a temporary file.'
-io.type = 'Checks whether `obj` is a valid file handle.'
-io.write = 'Writes the value of each of its arguments to default output file.'
-openmode.r = 'Read mode.'
-openmode.w = 'Write mode.'
-openmode.a = 'Append mode.'
-openmode['.r+'] = 'Update mode, all previous data is preserved.'
-openmode['.w+'] = 'Update mode, all previous data is erased.'
-openmode['.a+'] = 'Append update mode, previous data is preserved, writing is only allowed at the end of file.'
-openmode.rb = 'Read mode. (in binary mode.)'
-openmode.wb = 'Write mode. (in binary mode.)'
-openmode.ab = 'Append mode. (in binary mode.)'
-openmode['.r+b'] = 'Update mode, all previous data is preserved. (in binary mode.)'
-openmode['.w+b'] = 'Update mode, all previous data is erased. (in binary mode.)'
-openmode['.a+b'] = 'Append update mode, previous data is preserved, writing is only allowed at the end of file. (in binary mode.)'
-popenmode.r = 'Read data from this program by `file`.'
-popenmode.w = 'Write data to this program by `file`.'
-filetype.file = 'Is an open file handle.'
-filetype['.closed file'] = 'Is a closed file handle.'
-filetype['.nil'] = 'Is not a file handle.'
+io.open =
+'Opens a file, in the mode specified in the string `mode`.'
+io.output =
+'Sets `file` as the default output file.'
+io.popen =
+'Starts program prog in a separated process.'
+io.read =
+'Reads the `file`, according to the given formats, which specify what to read.'
+io.tmpfile =
+'In case of success, returns a handle for a temporary file.'
+io.type =
+'Checks whether `obj` is a valid file handle.'
+io.write =
+'Writes the value of each of its arguments to default output file.'
+openmode.r =
+'Read mode.'
+openmode.w =
+'Write mode.'
+openmode.a =
+'Append mode.'
+openmode['.r+'] =
+'Update mode, all previous data is preserved.'
+openmode['.w+'] =
+'Update mode, all previous data is erased.'
+openmode['.a+'] =
+'Append update mode, previous data is preserved, writing is only allowed at the end of file.'
+openmode.rb =
+'Read mode. (in binary mode.)'
+openmode.wb =
+'Write mode. (in binary mode.)'
+openmode.ab =
+'Append mode. (in binary mode.)'
+openmode['.r+b'] =
+'Update mode, all previous data is preserved. (in binary mode.)'
+openmode['.w+b'] =
+'Update mode, all previous data is erased. (in binary mode.)'
+openmode['.a+b'] =
+'Append update mode, previous data is preserved, writing is only allowed at the end of file. (in binary mode.)'
+popenmode.r =
+'Read data from this program by `file`.'
+popenmode.w =
+'Write data to this program by `file`.'
+filetype.file =
+'Is an open file handle.'
+filetype['.closed file'] =
+'Is a closed file handle.'
+filetype['.nil'] =
+'Is not a file handle.'
-math = ''
-math.abs = 'Returns the absolute value of `x`.'
-math.acos = 'Returns the arc cosine of `x` (in radians).'
-math.asin = 'Returns the arc sine of `x` (in radians).'
-math.atan['<5.2'] = 'Returns the arc tangent of `x` (in radians).'
-math.atan['>5.3'] = 'Returns the arc tangent of `y/x` (in radians).'
-math.atan2 = 'Returns the arc tangent of `y/x` (in radians).'
-math.ceil = 'Returns the smallest integral value larger than or equal to `x`.'
-math.cos = 'Returns the cosine of `x` (assumed to be in radians).'
-math.cosh = 'Returns the hyperbolic cosine of `x` (assumed to be in radians).'
-math.deg = 'Converts the angle `x` from radians to degrees.'
-math.exp = 'Returns the value `e^x` (where `e` is the base of natural logarithms).'
-math.floor = 'Returns the largest integral value smaller than or equal to `x`.'
-math.fmod = 'Returns the remainder of the division of `x` by `y` that rounds the quotient towards zero.'
-math.frexp = 'Decompose `x` into tails and exponents. Returns `m` and `e` such that `x = m * (2 ^ e)`, `e` is an integer and the absolute value of `m` is in the range [0.5, 1) (or zero when `x` is zero).'
-math.huge = 'A value larger than any other numeric value.'
-math.ldexp = 'Returns `m * (2 ^ e)` .'
-math.log['<5.1'] = 'Returns the natural logarithm of `x` .'
-math.log['>5.2'] = 'Returns the logarithm of `x` in the given base.'
-math.log10 = 'Returns the base-10 logarithm of x.'
-math.max = 'Returns the argument with the maximum value, according to the Lua operator `<`.'
-math.maxinteger = 'An integer with the maximum value for an integer.'
-math.min = 'Returns the argument with the minimum value, according to the Lua operator `<`.'
-math.mininteger = 'An integer with the minimum value for an integer.'
-math.modf = 'Returns the integral part of `x` and the fractional part of `x`.'
-math.pi = 'The value of *π*.'
-math.pow = 'Returns `x ^ y` .'
-math.rad = 'Converts the angle `x` from degrees to radians.'
-math.random = [[
+math =
+''
+math.abs =
+'Returns the absolute value of `x`.'
+math.acos =
+'Returns the arc cosine of `x` (in radians).'
+math.asin =
+'Returns the arc sine of `x` (in radians).'
+math.atan['<5.2'] =
+'Returns the arc tangent of `x` (in radians).'
+math.atan['>5.3'] =
+'Returns the arc tangent of `y/x` (in radians).'
+math.atan2 =
+'Returns the arc tangent of `y/x` (in radians).'
+math.ceil =
+'Returns the smallest integral value larger than or equal to `x`.'
+math.cos =
+'Returns the cosine of `x` (assumed to be in radians).'
+math.cosh =
+'Returns the hyperbolic cosine of `x` (assumed to be in radians).'
+math.deg =
+'Converts the angle `x` from radians to degrees.'
+math.exp =
+'Returns the value `e^x` (where `e` is the base of natural logarithms).'
+math.floor =
+'Returns the largest integral value smaller than or equal to `x`.'
+math.fmod =
+'Returns the remainder of the division of `x` by `y` that rounds the quotient towards zero.'
+math.frexp =
+'Decompose `x` into tails and exponents. Returns `m` and `e` such that `x = m * (2 ^ e)`, `e` is an integer and the absolute value of `m` is in the range [0.5, 1) (or zero when `x` is zero).'
+math.huge =
+'A value larger than any other numeric value.'
+math.ldexp =
+'Returns `m * (2 ^ e)` .'
+math.log['<5.1'] =
+'Returns the natural logarithm of `x` .'
+math.log['>5.2'] =
+'Returns the logarithm of `x` in the given base.'
+math.log10 =
+'Returns the base-10 logarithm of x.'
+math.max =
+'Returns the argument with the maximum value, according to the Lua operator `<`.'
+math.maxinteger =
+'An integer with the maximum value for an integer.'
+math.min =
+'Returns the argument with the minimum value, according to the Lua operator `<`.'
+math.mininteger =
+'An integer with the minimum value for an integer.'
+math.modf =
+'Returns the integral part of `x` and the fractional part of `x`.'
+math.pi =
+'The value of *π*.'
+math.pow =
+'Returns `x ^ y` .'
+math.rad =
+'Converts the angle `x` from degrees to radians.'
+math.random =
+[[
* `math.random()`: Returns a float in the range [0,1).
* `math.random(n)`: Returns a integer in the range [1, n].
* `math.random(m, n)`: Returns a integer in the range [m, n].
]]
-math.randomseed['<5.3'] = 'Sets `x` as the "seed" for the pseudo-random generator.'
-math.randomseed['>5.4'] = [[
+math.randomseed['<5.3'] =
+'Sets `x` as the "seed" for the pseudo-random generator.'
+math.randomseed['>5.4'] =
+[[
* `math.randomseed(x, y)`: Concatenate `x` and `y` into a 128-bit `seed` to reinitialize the pseudo-random generator.
* `math.randomseed(x)`: Equate to `math.randomseed(x, 0)` .
* `math.randomseed()`: Generates a seed with a weak attempt for randomness.
]]
-math.sin = 'Returns the sine of `x` (assumed to be in radians).'
-math.sinh = 'Returns the hyperbolic sine of `x` (assumed to be in radians).'
-math.sqrt = 'Returns the square root of `x`.'
-math.tan = 'Returns the tangent of `x` (assumed to be in radians).'
-math.tanh = 'Returns the hyperbolic tangent of `x` (assumed to be in radians).'
-math.tointeger = 'If the value `x` is convertible to an integer, returns that integer.'
-math.type = 'Returns `"integer"` if `x` is an integer, `"float"` if it is a float, or `nil` if `x` is not a number.'
-math.ult = 'Returns `true` if and only if `m` is below `n` when they are compared as unsigned integers.'
+math.sin =
+'Returns the sine of `x` (assumed to be in radians).'
+math.sinh =
+'Returns the hyperbolic sine of `x` (assumed to be in radians).'
+math.sqrt =
+'Returns the square root of `x`.'
+math.tan =
+'Returns the tangent of `x` (assumed to be in radians).'
+math.tanh =
+'Returns the hyperbolic tangent of `x` (assumed to be in radians).'
+math.tointeger =
+'If the value `x` is convertible to an integer, returns that integer.'
+math.type =
+'Returns `"integer"` if `x` is an integer, `"float"` if it is a float, or `nil` if `x` is not a number.'
+math.ult =
+'Returns `true` if and only if `m` is below `n` when they are compared as unsigned integers.'
-os = ''
-os.clock = 'Returns an approximation of the amount in seconds of CPU time used by the program.'
-os.date = 'Returns a string or a table containing date and time, formatted according to the given string `format`.'
-os.difftime = 'Returns the difference, in seconds, from time `t1` to time `t2`.'
-os.execute = 'Passes `command` to be executed by an operating system shell.'
-os.exit['<5.1'] = 'Calls the C function `exit` to terminate the host program.'
-os.exit['>5.2'] = 'Calls the ISO C function `exit` to terminate the host program.'
-os.getenv = 'Returns the value of the process environment variable `varname`.'
-os.remove = 'Deletes the file with the given name.'
-os.rename = 'Renames the file or directory named `oldname` to `newname`.'
-os.setlocale = 'Sets the current locale of the program.'
-os.time = 'Returns the current time when called without arguments, or a time representing the local date and time specified by the given table.'
-os.tmpname = 'Returns a string with a file name that can be used for a temporary file.'
-osdate.year = 'four digits'
-osdate.month = '1-12'
-osdate.day = '1-31'
-osdate.hour = '0-23'
-osdate.min = '0-59'
-osdate.sec = '0-61'
-osdate.wday = 'weekday, 1–7, Sunday is 1'
-osdate.yday = 'day of the year, 1–366'
-osdate.isdst = 'daylight saving flag, a boolean'
+os =
+''
+os.clock =
+'Returns an approximation of the amount in seconds of CPU time used by the program.'
+os.date =
+'Returns a string or a table containing date and time, formatted according to the given string `format`.'
+os.difftime =
+'Returns the difference, in seconds, from time `t1` to time `t2`.'
+os.execute =
+'Passes `command` to be executed by an operating system shell.'
+os.exit['<5.1'] =
+'Calls the C function `exit` to terminate the host program.'
+os.exit['>5.2'] =
+'Calls the ISO C function `exit` to terminate the host program.'
+os.getenv =
+'Returns the value of the process environment variable `varname`.'
+os.remove =
+'Deletes the file with the given name.'
+os.rename =
+'Renames the file or directory named `oldname` to `newname`.'
+os.setlocale =
+'Sets the current locale of the program.'
+os.time =
+'Returns the current time when called without arguments, or a time representing the local date and time specified by the given table.'
+os.tmpname =
+'Returns a string with a file name that can be used for a temporary file.'
+osdate.year =
+'four digits'
+osdate.month =
+'1-12'
+osdate.day =
+'1-31'
+osdate.hour =
+'0-23'
+osdate.min =
+'0-59'
+osdate.sec =
+'0-61'
+osdate.wday =
+'weekday, 1–7, Sunday is 1'
+osdate.yday =
+'day of the year, 1–366'
+osdate.isdst =
+'daylight saving flag, a boolean'
-package = ''
-require['<5.3'] = 'Loads the given module, returns any value returned by the given module(`true` when `nil`).'
-require['>5.4'] = 'Loads the given module, returns any value returned by the searcher(`true` when `nil`). Besides that value, also returns as a second result the loader data returned by the searcher, which indicates how `require` found the module. (For instance, if the module came from a file, this loader data is the file path.)'
-package.config = 'A string describing some compile-time configurations for packages.'
-package.cpath = 'The path used by `require` to search for a C loader.'
-package.loaded = 'A table used by `require` to control which modules are already loaded.'
-package.loaders = 'A table used by `require` to control how to load modules.'
-package.loadlib = 'Dynamically links the host program with the C library `libname`.'
-package.path = 'The path used by `require` to search for a Lua loader.'
-package.preload = 'A table to store loaders for specific modules.'
-package.searchers = 'A table used by `require` to control how to load modules.'
-package.searchpath = 'Searches for the given `name` in the given `path`.'
-package.seeall = 'Sets a metatable for `module` with its `__index` field referring to the global environment, so that this module inherits values from the global environment. To be used as an option to function `module` .'
+package =
+''
+require['<5.3'] =
+'Loads the given module, returns any value returned by the given module(`true` when `nil`).'
+require['>5.4'] =
+'Loads the given module, returns any value returned by the searcher(`true` when `nil`). Besides that value, also returns as a second result the loader data returned by the searcher, which indicates how `require` found the module. (For instance, if the module came from a file, this loader data is the file path.)'
+package.config =
+'A string describing some compile-time configurations for packages.'
+package.cpath =
+'The path used by `require` to search for a C loader.'
+package.loaded =
+'A table used by `require` to control which modules are already loaded.'
+package.loaders =
+'A table used by `require` to control how to load modules.'
+package.loadlib =
+'Dynamically links the host program with the C library `libname`.'
+package.path =
+'The path used by `require` to search for a Lua loader.'
+package.preload =
+'A table to store loaders for specific modules.'
+package.searchers =
+'A table used by `require` to control how to load modules.'
+package.searchpath =
+'Searches for the given `name` in the given `path`.'
+package.seeall =
+'Sets a metatable for `module` with its `__index` field referring to the global environment, so that this module inherits values from the global environment. To be used as an option to function `module` .'
-string = ''
-string.byte = 'Returns the internal numeric codes of the characters `s[i], s[i+1], ..., s[j]`.'
-string.char = 'Returns a string with length equal to the number of arguments, in which each character has the internal numeric code equal to its corresponding argument.'
-string.dump = 'Returns a string containing a binary representation (a *binary chunk*) of the given function.'
-string.find = 'Looks for the first match of `pattern` (see §6.4.1) in the string.'
-string.format = 'Returns a formatted version of its variable number of arguments following the description given in its first argument.'
-string.gmatch = [[
+string =
+''
+string.byte =
+'Returns the internal numeric codes of the characters `s[i], s[i+1], ..., s[j]`.'
+string.char =
+'Returns a string with length equal to the number of arguments, in which each character has the internal numeric code equal to its corresponding argument.'
+string.dump =
+'Returns a string containing a binary representation (a *binary chunk*) of the given function.'
+string.find =
+'Looks for the first match of `pattern` (see §6.4.1) in the string.'
+string.format =
+'Returns a formatted version of its variable number of arguments following the description given in its first argument.'
+string.gmatch =
+[[
Returns an iterator function that, each time it is called, returns the next captures from `pattern` (see §6.4.1) over the string s.
As an example, the following loop will iterate over all the words from string s, printing one per line:
```lua
- s = "hello world from Lua"
+ s =
+"hello world from Lua"
for w in string.gmatch(s, "%a+") do
print(w)
end
```
]]
-string.gsub = 'Returns a copy of s in which all (or the first `n`, if given) occurrences of the `pattern` (see §6.4.1) have been replaced by a replacement string specified by `repl`.'
-string.len = 'Returns its length.'
-string.lower = 'Returns a copy of this string with all uppercase letters changed to lowercase.'
-string.match = 'Looks for the first match of `pattern` (see §6.4.1) in the string.'
-string.pack = 'Returns a binary string containing the values `v1`, `v2`, etc. packed (that is, serialized in binary form) according to the format string `fmt` (see §6.4.2) .'
-string.packsize = 'Returns the size of a string resulting from `string.pack` with the given format string `fmt` (see §6.4.2) .'
-string.rep['>5.2'] = 'Returns a string that is the concatenation of `n` copies of the string `s` separated by the string `sep`.'
-string.rep['<5.1'] = 'Returns a string that is the concatenation of `n` copies of the string `s` .'
-string.reverse = 'Returns a string that is the string `s` reversed.'
-string.sub = 'Returns the substring of the string that starts at `i` and continues until `j`.'
-string.unpack = 'Returns the values packed in string according to the format string `fmt` (see §6.4.2) .'
-string.upper = 'Returns a copy of this string with all lowercase letters changed to uppercase.'
+string.gsub =
+'Returns a copy of s in which all (or the first `n`, if given) occurrences of the `pattern` (see §6.4.1) have been replaced by a replacement string specified by `repl`.'
+string.len =
+'Returns its length.'
+string.lower =
+'Returns a copy of this string with all uppercase letters changed to lowercase.'
+string.match =
+'Looks for the first match of `pattern` (see §6.4.1) in the string.'
+string.pack =
+'Returns a binary string containing the values `v1`, `v2`, etc. packed (that is, serialized in binary form) according to the format string `fmt` (see §6.4.2) .'
+string.packsize =
+'Returns the size of a string resulting from `string.pack` with the given format string `fmt` (see §6.4.2) .'
+string.rep['>5.2'] =
+'Returns a string that is the concatenation of `n` copies of the string `s` separated by the string `sep`.'
+string.rep['<5.1'] =
+'Returns a string that is the concatenation of `n` copies of the string `s` .'
+string.reverse =
+'Returns a string that is the string `s` reversed.'
+string.sub =
+'Returns the substring of the string that starts at `i` and continues until `j`.'
+string.unpack =
+'Returns the values packed in string according to the format string `fmt` (see §6.4.2) .'
+string.upper =
+'Returns a copy of this string with all lowercase letters changed to uppercase.'
-table = ''
-table.concat = 'Given a list where all elements are strings or numbers, returns the string `list[i]..sep..list[i+1] ··· sep..list[j]`.'
-table.insert = 'Inserts element `value` at position `pos` in `list`.'
-table.maxn = 'Returns the largest positive numerical index of the given table, or zero if the table has no positive numerical indices.'
-table.move = [[
+table =
+''
+table.concat =
+'Given a list where all elements are strings or numbers, returns the string `list[i]..sep..list[i+1] ··· sep..list[j]`.'
+table.insert =
+'Inserts element `value` at position `pos` in `list`.'
+table.maxn =
+'Returns the largest positive numerical index of the given table, or zero if the table has no positive numerical indices.'
+table.move =
+[[
Moves elements from table `a1` to table `a2`.
```lua
-a2[t],··· = a1[f],···,a1[e]
+a2[t],··· =
+a1[f],···,a1[e]
return a2
```
]]
-table.pack = 'Returns a new table with all arguments stored into keys `1`, `2`, etc. and with a field `"n"` with the total number of arguments.'
-table.remove = 'Removes from `list` the element at position `pos`, returning the value of the removed element.'
-table.sort = 'Sorts list elements in a given order, *in-place*, from `list[1]` to `list[#list]`.'
-table.unpack = [[
+table.pack =
+'Returns a new table with all arguments stored into keys `1`, `2`, etc. and with a field `"n"` with the total number of arguments.'
+table.remove =
+'Removes from `list` the element at position `pos`, returning the value of the removed element.'
+table.sort =
+'Sorts list elements in a given order, *in-place*, from `list[1]` to `list[#list]`.'
+table.unpack =
+[[
Returns the elements from the given list. This function is equivalent to
```lua
return list[i], list[i+1], ···, list[j]
@@ -413,10 +678,14 @@ Returns the elements from the given list. This function is equivalent to
By default, `i` is `1` and `j` is `#list`.
]]
-utf8 = ''
-utf8.char = 'Receives zero or more integers, converts each one to its corresponding UTF-8 byte sequence and returns a string with the concatenation of all these sequences.'
-utf8.charpattern = 'The pattern which matches exactly one UTF-8 byte sequence, assuming that the subject is a valid UTF-8 string.'
-utf8.codes = [[
+utf8 =
+''
+utf8.char =
+'Receives zero or more integers, converts each one to its corresponding UTF-8 byte sequence and returns a string with the concatenation of all these sequences.'
+utf8.charpattern =
+'The pattern which matches exactly one UTF-8 byte sequence, assuming that the subject is a valid UTF-8 string.'
+utf8.codes =
+[[
Returns values so that the construction
```lua
for p, c in utf8.codes(s) do
@@ -425,6 +694,9 @@ end
```
will iterate over all UTF-8 characters in string s, with p being the position (in bytes) and c the code point of each character. It raises an error if it meets any invalid byte sequence.
]]
-utf8.codepoint = 'Returns the codepoints (as integers) from all characters in `s` that start between byte position `i` and `j` (both included).'
-utf8.len = 'Returns the number of UTF-8 characters in string `s` that start between positions `i` and `j` (both inclusive).'
-utf8.offset = 'Returns the position (in bytes) where the encoding of the `n`-th character of `s` (counting from position `i`) starts.'
+utf8.codepoint =
+'Returns the codepoints (as integers) from all characters in `s` that start between byte position `i` and `j` (both included).'
+utf8.len =
+'Returns the number of UTF-8 characters in string `s` that start between positions `i` and `j` (both inclusive).'
+utf8.offset =
+'Returns the position (in bytes) where the encoding of the `n`-th character of `s` (counting from position `i`) starts.'
diff --git a/locale/en-us/script.lua b/locale/en-us/script.lua
index bb77b308..6775bbe9 100644
--- a/locale/en-us/script.lua
+++ b/locale/en-us/script.lua
@@ -1,272 +1,513 @@
-DIAG_LINE_ONLY_SPACE = 'Line with spaces only.'
-DIAG_LINE_POST_SPACE = 'Line with postspace.'
-DIAG_UNUSED_LOCAL = 'Unused local `{}`.'
-DIAG_UNDEF_GLOBAL = 'Undefined global `{}`.'
-DIAG_UNDEF_FIELD = 'Undefined field `{}`.'
-DIAG_UNDEF_ENV_CHILD = 'Undefined variable `{}` (overloaded `_ENV` ).'
-DIAG_UNDEF_FENV_CHILD = 'Undefined variable `{}` (inside module).'
-DIAG_GLOBAL_IN_NIL_ENV = 'Invalid global (`_ENV` is `nil`).'
-DIAG_GLOBAL_IN_NIL_FENV = 'Invalid global (module environment is `nil`).'
-DIAG_UNUSED_LABEL = 'Unused label `{}`.'
-DIAG_UNUSED_FUNCTION = 'Unused functions.'
-DIAG_UNUSED_VARARG = 'Unused vararg.'
-DIAG_REDEFINED_LOCAL = 'Redefined local `{}`.'
-DIAG_DUPLICATE_INDEX = 'Duplicate index `{}`.'
-DIAG_DUPLICATE_METHOD = 'Duplicate method `{}`.'
-DIAG_PREVIOUS_CALL = 'Will be interpreted as `{}{}`. It may be necessary to add a `,`.'
-DIAG_PREFIELD_CALL = 'Will be interpreted as `{}{}`. It may be necessary to add a `,` or `;`.'
-DIAG_OVER_MAX_ARGS = 'The function takes only {:d} parameters, but you passed {:d}.'
-DIAG_OVER_MAX_ARGS = 'Only has {} variables, but you set {} values.'
-DIAG_AMBIGUITY_1 = 'Compute `{}` first. You may need to add brackets.'
-DIAG_LOWERCASE_GLOBAL = 'Global variable in lowercase initial, Did you miss `local` or misspell it?'
-DIAG_EMPTY_BLOCK = 'Empty block.'
-DIAG_DIAGNOSTICS = 'Lua Diagnostics.'
-DIAG_SYNTAX_CHECK = 'Lua Syntax Check.'
-DIAG_NEED_VERSION = 'Supported in {}, current is {}.'
-DIAG_DEFINED_VERSION = 'Defined in {}, current is {}.'
-DIAG_DEFINED_CUSTOM = 'Defined in {}.'
-DIAG_DUPLICATE_CLASS = 'Duplicate Class `{}`.'
-DIAG_UNDEFINED_CLASS = 'Undefined Class `{}`.'
-DIAG_CYCLIC_EXTENDS = 'Cyclic extends.'
-DIAG_INEXISTENT_PARAM = 'Inexistent param.'
-DIAG_DUPLICATE_PARAM = 'Duplicate param.'
-DIAG_NEED_CLASS = 'Class needs to be defined first.'
-DIAG_DUPLICATE_SET_FIELD= 'Duplicate field `{}`.'
-DIAG_SET_CONST = 'Assignment to const variable.'
-DIAG_SET_FOR_STATE = 'Assignment to for-state variable.'
-DIAG_CODE_AFTER_BREAK = 'Unable to execute code after `break`.'
-DIAG_UNBALANCED_ASSIGNMENTS = 'The value is assigned as `nil` because the number of values is not enough. In Lua, `x, y = 1 ` is equivalent to `x, y = 1, nil` .'
-DIAG_REQUIRE_LIKE = 'You can treat `{}` as `require` by setting.'
-DIAG_COSE_NON_OBJECT = 'Cannot close a value of this type. (Unless set `__close` meta method)'
-DIAG_COUNT_DOWN_LOOP = 'Do you mean `{}` ?'
-DIAG_IMPLICIT_ANY = 'Can not infer type.'
-DIAG_DEPRECATED = 'Deprecated.'
-DIAG_DIFFERENT_REQUIRES = 'The same file is required with different names.'
-DIAG_REDUNDANT_RETURN = 'Redundant return.'
-DIAG_AWAIT_IN_SYNC = 'Async function can only be called in async function.'
-DIAG_NOT_YIELDABLE = 'The {}th parameter of this function was not marked as yieldable, but an async function was passed in. (Use `---@param name async fun()` to mark as yieldable)'
-DIAG_DISCARD_RETURNS = 'The return values of this function cannot be discarded.'
+DIAG_LINE_ONLY_SPACE =
+'Line with spaces only.'
+DIAG_LINE_POST_SPACE =
+'Line with postspace.'
+DIAG_UNUSED_LOCAL =
+'Unused local `{}`.'
+DIAG_UNDEF_GLOBAL =
+'Undefined global `{}`.'
+DIAG_UNDEF_FIELD =
+'Undefined field `{}`.'
+DIAG_UNDEF_ENV_CHILD =
+'Undefined variable `{}` (overloaded `_ENV` ).'
+DIAG_UNDEF_FENV_CHILD =
+'Undefined variable `{}` (inside module).'
+DIAG_GLOBAL_IN_NIL_ENV =
+'Invalid global (`_ENV` is `nil`).'
+DIAG_GLOBAL_IN_NIL_FENV =
+'Invalid global (module environment is `nil`).'
+DIAG_UNUSED_LABEL =
+'Unused label `{}`.'
+DIAG_UNUSED_FUNCTION =
+'Unused functions.'
+DIAG_UNUSED_VARARG =
+'Unused vararg.'
+DIAG_REDEFINED_LOCAL =
+'Redefined local `{}`.'
+DIAG_DUPLICATE_INDEX =
+'Duplicate index `{}`.'
+DIAG_DUPLICATE_METHOD =
+'Duplicate method `{}`.'
+DIAG_PREVIOUS_CALL =
+'Will be interpreted as `{}{}`. It may be necessary to add a `,`.'
+DIAG_PREFIELD_CALL =
+'Will be interpreted as `{}{}`. It may be necessary to add a `,` or `;`.'
+DIAG_OVER_MAX_ARGS =
+'The function takes only {:d} parameters, but you passed {:d}.'
+DIAG_OVER_MAX_ARGS =
+'Only has {} variables, but you set {} values.'
+DIAG_AMBIGUITY_1 =
+'Compute `{}` first. You may need to add brackets.'
+DIAG_LOWERCASE_GLOBAL =
+'Global variable in lowercase initial, Did you miss `local` or misspell it?'
+DIAG_EMPTY_BLOCK =
+'Empty block.'
+DIAG_DIAGNOSTICS =
+'Lua Diagnostics.'
+DIAG_SYNTAX_CHECK =
+'Lua Syntax Check.'
+DIAG_NEED_VERSION =
+'Supported in {}, current is {}.'
+DIAG_DEFINED_VERSION =
+'Defined in {}, current is {}.'
+DIAG_DEFINED_CUSTOM =
+'Defined in {}.'
+DIAG_DUPLICATE_CLASS =
+'Duplicate Class `{}`.'
+DIAG_UNDEFINED_CLASS =
+'Undefined Class `{}`.'
+DIAG_CYCLIC_EXTENDS =
+'Cyclic extends.'
+DIAG_INEXISTENT_PARAM =
+'Inexistent param.'
+DIAG_DUPLICATE_PARAM =
+'Duplicate param.'
+DIAG_NEED_CLASS =
+'Class needs to be defined first.'
+DIAG_DUPLICATE_SET_FIELD=
+'Duplicate field `{}`.'
+DIAG_SET_CONST =
+'Assignment to const variable.'
+DIAG_SET_FOR_STATE =
+'Assignment to for-state variable.'
+DIAG_CODE_AFTER_BREAK =
+'Unable to execute code after `break`.'
+DIAG_UNBALANCED_ASSIGNMENTS =
+'The value is assigned as `nil` because the number of values is not enough. In Lua, `x, y = 1 ` is equivalent to `x, y = 1, nil` .'
+DIAG_REQUIRE_LIKE =
+'You can treat `{}` as `require` by setting.'
+DIAG_COSE_NON_OBJECT =
+'Cannot close a value of this type. (Unless set `__close` meta method)'
+DIAG_COUNT_DOWN_LOOP =
+'Do you mean `{}` ?'
+DIAG_IMPLICIT_ANY =
+'Can not infer type.'
+DIAG_DEPRECATED =
+'Deprecated.'
+DIAG_DIFFERENT_REQUIRES =
+'The same file is required with different names.'
+DIAG_REDUNDANT_RETURN =
+'Redundant return.'
+DIAG_AWAIT_IN_SYNC =
+'Async function can only be called in async function.'
+DIAG_NOT_YIELDABLE =
+'The {}th parameter of this function was not marked as yieldable, but an async function was passed in. (Use `---@param name async fun()` to mark as yieldable)'
+DIAG_DISCARD_RETURNS =
+'The return values of this function cannot be discarded.'
-DIAG_CIRCLE_DOC_CLASS = 'Circularly inherited classes.'
-DIAG_DOC_FIELD_NO_CLASS = 'The field must be defined after the class.'
-DIAG_DUPLICATE_DOC_CLASS = 'Duplicate defined class `{}`.'
-DIAG_DUPLICATE_DOC_FIELD = 'Duplicate defined fields `{}`.'
-DIAG_DUPLICATE_DOC_PARAM = 'Duplicate params `{}`.'
-DIAG_UNDEFINED_DOC_CLASS = 'Undefined class `{}`.'
-DIAG_UNDEFINED_DOC_NAME = 'Undefined type or alias `{}`.'
-DIAG_UNDEFINED_DOC_PARAM = 'Undefined param `{}`.'
-DIAG_UNKNOWN_DIAG_CODE = 'Unknown diagnostic code `{}`.'
+DIAG_CIRCLE_DOC_CLASS =
+'Circularly inherited classes.'
+DIAG_DOC_FIELD_NO_CLASS =
+'The field must be defined after the class.'
+DIAG_DUPLICATE_DOC_CLASS =
+'Duplicate defined class `{}`.'
+DIAG_DUPLICATE_DOC_FIELD =
+'Duplicate defined fields `{}`.'
+DIAG_DUPLICATE_DOC_PARAM =
+'Duplicate params `{}`.'
+DIAG_UNDEFINED_DOC_CLASS =
+'Undefined class `{}`.'
+DIAG_UNDEFINED_DOC_NAME =
+'Undefined type or alias `{}`.'
+DIAG_UNDEFINED_DOC_PARAM =
+'Undefined param `{}`.'
+DIAG_UNKNOWN_DIAG_CODE =
+'Unknown diagnostic code `{}`.'
-MWS_NOT_SUPPORT = '{} does not support multi workspace for now, I may need to restart to support the new workspace ...'
-MWS_RESTART = 'Restart'
-MWS_NOT_COMPLETE = 'Workspace is not complete yet. You may try again later...'
-MWS_COMPLETE = 'Workspace is complete now. You may try again...'
-MWS_MAX_PRELOAD = 'Preloaded files has reached the upper limit ({}), you need to manually open the files that need to be loaded.'
-MWS_UCONFIG_FAILED = 'Saving user setting failed.'
-MWS_UCONFIG_UPDATED = 'User setting updated.'
-MWS_WCONFIG_UPDATED = 'Workspace setting updated.'
+MWS_NOT_SUPPORT =
+'{} does not support multi workspace for now, I may need to restart to support the new workspace ...'
+MWS_RESTART =
+'Restart'
+MWS_NOT_COMPLETE =
+'Workspace is not complete yet. You may try again later...'
+MWS_COMPLETE =
+'Workspace is complete now. You may try again...'
+MWS_MAX_PRELOAD =
+'Preloaded files has reached the upper limit ({}), you need to manually open the files that need to be loaded.'
+MWS_UCONFIG_FAILED =
+'Saving user setting failed.'
+MWS_UCONFIG_UPDATED =
+'User setting updated.'
+MWS_WCONFIG_UPDATED =
+'Workspace setting updated.'
-WORKSPACE_SKIP_LARGE_FILE = 'Too large file: {} skipped. The currently set size limit is: {} KB, and the file size is: {} KB.'
-WORKSPACE_LOADING = 'Loading workspace'
-WORKSPACE_DIAGNOSTIC = 'Diagnosing workspace'
-WORKSPACE_SKIP_HUGE_FILE = 'For performance reasons, the parsing of this file has been stopped: {}'
+WORKSPACE_SKIP_LARGE_FILE =
+'Too large file: {} skipped. The currently set size limit is: {} KB, and the file size is: {} KB.'
+WORKSPACE_LOADING =
+'Loading workspace'
+WORKSPACE_DIAGNOSTIC =
+'Diagnosing workspace'
+WORKSPACE_SKIP_HUGE_FILE =
+'For performance reasons, the parsing of this file has been stopped: {}'
-PARSER_CRASH = 'Parser crashed! Last words:{}'
-PARSER_UNKNOWN = 'Unknown syntax error...'
-PARSER_MISS_NAME = '<name> expected.'
-PARSER_UNKNOWN_SYMBOL = 'Unexpected symbol `{symbol}`.'
-PARSER_MISS_SYMBOL = 'Missed symbol `{symbol}`.'
-PARSER_MISS_ESC_X = 'Should be 2 hexadecimal digits.'
-PARSER_UTF8_SMALL = 'At least 1 hexadecimal digit.'
-PARSER_UTF8_MAX = 'Should be between {min} and {max} .'
-PARSER_ERR_ESC = 'Invalid escape sequence.'
-PARSER_MUST_X16 = 'Should be hexadecimal digits.'
-PARSER_MISS_EXPONENT = 'Missed digits for the exponent.'
-PARSER_MISS_EXP = '<exp> expected.'
-PARSER_MISS_FIELD = '<field> expected.'
-PARSER_MISS_METHOD = '<method> expected.'
-PARSER_ARGS_AFTER_DOTS = '`...` should be the last arg.'
-PARSER_KEYWORD = '<keyword> cannot be used as name.'
-PARSER_EXP_IN_ACTION = 'Unexpected <exp> .'
-PARSER_BREAK_OUTSIDE = '<break> not inside a loop.'
-PARSER_MALFORMED_NUMBER = 'Malformed number.'
-PARSER_ACTION_AFTER_RETURN = '<eof> expected after `return`.'
-PARSER_ACTION_AFTER_BREAK = '<eof> expected after `break`.'
-PARSER_NO_VISIBLE_LABEL = 'No visible label `{label}` .'
-PARSER_REDEFINE_LABEL = 'Label `{label}` already defined.'
-PARSER_UNSUPPORT_SYMBOL = '{version} does not support this grammar.'
-PARSER_UNEXPECT_DOTS = 'Cannot use `...` outside a vararg function.'
-PARSER_UNEXPECT_SYMBOL = 'Unexpected symbol `{symbol}` .'
-PARSER_UNKNOWN_TAG = 'Unknown attribute.'
-PARSER_MULTI_TAG = 'Does not support multi attributes.'
-PARSER_UNEXPECT_LFUNC_NAME = 'Local function can only use identifiers as name.'
-PARSER_UNEXPECT_EFUNC_NAME = 'Function as expression cannot be named.'
-PARSER_ERR_LCOMMENT_END = 'Multi-line annotations should be closed by `{symbol}` .'
-PARSER_ERR_C_LONG_COMMENT = 'Lua should use `--[[ ]]` for multi-line annotations.'
-PARSER_ERR_LSTRING_END = 'Long string should be closed by `{symbol}` .'
-PARSER_ERR_ASSIGN_AS_EQ = 'Should use `=` for assignment.'
-PARSER_ERR_EQ_AS_ASSIGN = 'Should use `==` for equal.'
-PARSER_ERR_UEQ = 'Should use `~=` for not equal.'
-PARSER_ERR_THEN_AS_DO = 'Should use `then` .'
-PARSER_ERR_DO_AS_THEN = 'Should use `do` .'
-PARSER_MISS_END = 'Miss corresponding `end` .'
-PARSER_ERR_COMMENT_PREFIX = 'Lua should use `--` for annotations.'
-PARSER_MISS_SEP_IN_TABLE = 'Miss symbol `,` or `;` .'
-PARSER_SET_CONST = 'Assignment to const variable.'
-PARSER_UNICODE_NAME = 'Contains Unicode characters.'
-PARSER_ERR_NONSTANDARD_SYMBOL = 'Lua should use `{symbol}` .'
-PARSER_MISS_SPACE_BETWEEN = 'Spaces must be left between symbols.'
-PARSER_INDEX_IN_FUNC_NAME = 'The `[name]` form cannot be used in the name of a named function.'
-PARSER_UNKNOWN_ATTRIBUTE = 'Local attribute should be `const` or `close`'
+PARSER_CRASH =
+'Parser crashed! Last words:{}'
+PARSER_UNKNOWN =
+'Unknown syntax error...'
+PARSER_MISS_NAME =
+'<name> expected.'
+PARSER_UNKNOWN_SYMBOL =
+'Unexpected symbol `{symbol}`.'
+PARSER_MISS_SYMBOL =
+'Missed symbol `{symbol}`.'
+PARSER_MISS_ESC_X =
+'Should be 2 hexadecimal digits.'
+PARSER_UTF8_SMALL =
+'At least 1 hexadecimal digit.'
+PARSER_UTF8_MAX =
+'Should be between {min} and {max} .'
+PARSER_ERR_ESC =
+'Invalid escape sequence.'
+PARSER_MUST_X16 =
+'Should be hexadecimal digits.'
+PARSER_MISS_EXPONENT =
+'Missed digits for the exponent.'
+PARSER_MISS_EXP =
+'<exp> expected.'
+PARSER_MISS_FIELD =
+'<field> expected.'
+PARSER_MISS_METHOD =
+'<method> expected.'
+PARSER_ARGS_AFTER_DOTS =
+'`...` should be the last arg.'
+PARSER_KEYWORD =
+'<keyword> cannot be used as name.'
+PARSER_EXP_IN_ACTION =
+'Unexpected <exp> .'
+PARSER_BREAK_OUTSIDE =
+'<break> not inside a loop.'
+PARSER_MALFORMED_NUMBER =
+'Malformed number.'
+PARSER_ACTION_AFTER_RETURN =
+'<eof> expected after `return`.'
+PARSER_ACTION_AFTER_BREAK =
+'<eof> expected after `break`.'
+PARSER_NO_VISIBLE_LABEL =
+'No visible label `{label}` .'
+PARSER_REDEFINE_LABEL =
+'Label `{label}` already defined.'
+PARSER_UNSUPPORT_SYMBOL =
+'{version} does not support this grammar.'
+PARSER_UNEXPECT_DOTS =
+'Cannot use `...` outside a vararg function.'
+PARSER_UNEXPECT_SYMBOL =
+'Unexpected symbol `{symbol}` .'
+PARSER_UNKNOWN_TAG =
+'Unknown attribute.'
+PARSER_MULTI_TAG =
+'Does not support multi attributes.'
+PARSER_UNEXPECT_LFUNC_NAME =
+'Local function can only use identifiers as name.'
+PARSER_UNEXPECT_EFUNC_NAME =
+'Function as expression cannot be named.'
+PARSER_ERR_LCOMMENT_END =
+'Multi-line annotations should be closed by `{symbol}` .'
+PARSER_ERR_C_LONG_COMMENT =
+'Lua should use `--[[ ]]` for multi-line annotations.'
+PARSER_ERR_LSTRING_END =
+'Long string should be closed by `{symbol}` .'
+PARSER_ERR_ASSIGN_AS_EQ =
+'Should use `=` for assignment.'
+PARSER_ERR_EQ_AS_ASSIGN =
+'Should use `==` for equal.'
+PARSER_ERR_UEQ =
+'Should use `~=` for not equal.'
+PARSER_ERR_THEN_AS_DO =
+'Should use `then` .'
+PARSER_ERR_DO_AS_THEN =
+'Should use `do` .'
+PARSER_MISS_END =
+'Miss corresponding `end` .'
+PARSER_ERR_COMMENT_PREFIX =
+'Lua should use `--` for annotations.'
+PARSER_MISS_SEP_IN_TABLE =
+'Miss symbol `,` or `;` .'
+PARSER_SET_CONST =
+'Assignment to const variable.'
+PARSER_UNICODE_NAME =
+'Contains Unicode characters.'
+PARSER_ERR_NONSTANDARD_SYMBOL =
+'Lua should use `{symbol}` .'
+PARSER_MISS_SPACE_BETWEEN =
+'Spaces must be left between symbols.'
+PARSER_INDEX_IN_FUNC_NAME =
+'The `[name]` form cannot be used in the name of a named function.'
+PARSER_UNKNOWN_ATTRIBUTE =
+'Local attribute should be `const` or `close`'
-PARSER_LUADOC_MISS_CLASS_NAME = '<class name> expected.'
-PARSER_LUADOC_MISS_EXTENDS_SYMBOL = '`:` expected.'
-PARSER_LUADOC_MISS_CLASS_EXTENDS_NAME = '<class extends name> expected.'
-PARSER_LUADOC_MISS_SYMBOL = '`{symbol}` expected.'
-PARSER_LUADOC_MISS_ARG_NAME = '<arg name> expected.'
-PARSER_LUADOC_MISS_TYPE_NAME = '<type name> expected.'
-PARSER_LUADOC_MISS_ALIAS_NAME = '<alias name> expected.'
-PARSER_LUADOC_MISS_ALIAS_EXTENDS = '<alias extends> expected.'
-PARSER_LUADOC_MISS_PARAM_NAME = '<param name> expected.'
-PARSER_LUADOC_MISS_PARAM_EXTENDS = '<param extends> expected.'
-PARSER_LUADOC_MISS_FIELD_NAME = '<field name> expected.'
-PARSER_LUADOC_MISS_FIELD_EXTENDS = '<field extends> expected.'
-PARSER_LUADOC_MISS_GENERIC_NAME = '<generic name> expected.'
-PARSER_LUADOC_MISS_GENERIC_EXTENDS_NAME = '<generic extends name> expected.'
-PARSER_LUADOC_MISS_VARARG_TYPE = '<vararg type> expected.'
-PARSER_LUADOC_MISS_FUN_AFTER_OVERLOAD = '`fun` expected.'
-PARSER_LUADOC_MISS_CATE_NAME = '<doc name> expected.'
-PARSER_LUADOC_MISS_DIAG_MODE = '<diagnostic mode> expected.'
-PARSER_LUADOC_ERROR_DIAG_MODE = '<diagnostic mode> incorrect.'
+PARSER_LUADOC_MISS_CLASS_NAME =
+'<class name> expected.'
+PARSER_LUADOC_MISS_EXTENDS_SYMBOL =
+'`:` expected.'
+PARSER_LUADOC_MISS_CLASS_EXTENDS_NAME =
+'<class extends name> expected.'
+PARSER_LUADOC_MISS_SYMBOL =
+'`{symbol}` expected.'
+PARSER_LUADOC_MISS_ARG_NAME =
+'<arg name> expected.'
+PARSER_LUADOC_MISS_TYPE_NAME =
+'<type name> expected.'
+PARSER_LUADOC_MISS_ALIAS_NAME =
+'<alias name> expected.'
+PARSER_LUADOC_MISS_ALIAS_EXTENDS =
+'<alias extends> expected.'
+PARSER_LUADOC_MISS_PARAM_NAME =
+'<param name> expected.'
+PARSER_LUADOC_MISS_PARAM_EXTENDS =
+'<param extends> expected.'
+PARSER_LUADOC_MISS_FIELD_NAME =
+'<field name> expected.'
+PARSER_LUADOC_MISS_FIELD_EXTENDS =
+'<field extends> expected.'
+PARSER_LUADOC_MISS_GENERIC_NAME =
+'<generic name> expected.'
+PARSER_LUADOC_MISS_GENERIC_EXTENDS_NAME =
+'<generic extends name> expected.'
+PARSER_LUADOC_MISS_VARARG_TYPE =
+'<vararg type> expected.'
+PARSER_LUADOC_MISS_FUN_AFTER_OVERLOAD =
+'`fun` expected.'
+PARSER_LUADOC_MISS_CATE_NAME =
+'<doc name> expected.'
+PARSER_LUADOC_MISS_DIAG_MODE =
+'<diagnostic mode> expected.'
+PARSER_LUADOC_ERROR_DIAG_MODE =
+'<diagnostic mode> incorrect.'
-SYMBOL_ANONYMOUS = '<Anonymous>'
+SYMBOL_ANONYMOUS =
+'<Anonymous>'
-HOVER_VIEW_DOCUMENTS = 'View documents'
+HOVER_VIEW_DOCUMENTS =
+'View documents'
-HOVER_DOCUMENT_LUA51 = 'http://www.lua.org/manual/5.1/manual.html#{}'
-HOVER_DOCUMENT_LUA52 = 'http://www.lua.org/manual/5.2/manual.html#{}'
-HOVER_DOCUMENT_LUA53 = 'http://www.lua.org/manual/5.3/manual.html#{}'
-HOVER_DOCUMENT_LUA54 = 'http://www.lua.org/manual/5.4/manual.html#{}'
-HOVER_DOCUMENT_LUAJIT = 'http://www.lua.org/manual/5.1/manual.html#{}'
+HOVER_DOCUMENT_LUA51 =
+'http://www.lua.org/manual/5.1/manual.html#{}'
+HOVER_DOCUMENT_LUA52 =
+'http://www.lua.org/manual/5.2/manual.html#{}'
+HOVER_DOCUMENT_LUA53 =
+'http://www.lua.org/manual/5.3/manual.html#{}'
+HOVER_DOCUMENT_LUA54 =
+'http://www.lua.org/manual/5.4/manual.html#{}'
+HOVER_DOCUMENT_LUAJIT =
+'http://www.lua.org/manual/5.1/manual.html#{}'
-HOVER_NATIVE_DOCUMENT_LUA51 = 'command:extension.lua.doc?["en-us/51/manual.html/{}"]'
-HOVER_NATIVE_DOCUMENT_LUA52 = 'command:extension.lua.doc?["en-us/52/manual.html/{}"]'
-HOVER_NATIVE_DOCUMENT_LUA53 = 'command:extension.lua.doc?["en-us/53/manual.html/{}"]'
-HOVER_NATIVE_DOCUMENT_LUA54 = 'command:extension.lua.doc?["en-us/54/manual.html/{}"]'
-HOVER_NATIVE_DOCUMENT_LUAJIT = 'command:extension.lua.doc?["en-us/51/manual.html/{}"]'
+HOVER_NATIVE_DOCUMENT_LUA51 =
+'command:extension.lua.doc?["en-us/51/manual.html/{}"]'
+HOVER_NATIVE_DOCUMENT_LUA52 =
+'command:extension.lua.doc?["en-us/52/manual.html/{}"]'
+HOVER_NATIVE_DOCUMENT_LUA53 =
+'command:extension.lua.doc?["en-us/53/manual.html/{}"]'
+HOVER_NATIVE_DOCUMENT_LUA54 =
+'command:extension.lua.doc?["en-us/54/manual.html/{}"]'
+HOVER_NATIVE_DOCUMENT_LUAJIT =
+'command:extension.lua.doc?["en-us/51/manual.html/{}"]'
-HOVER_MULTI_PROTOTYPE = '({} prototypes)'
-HOVER_STRING_BYTES = '{} bytes'
-HOVER_STRING_CHARACTERS = '{} bytes, {} characters'
-HOVER_MULTI_DEF_PROTO = '({} definitions, {} prototypes)'
-HOVER_MULTI_PROTO_NOT_FUNC = '({} non functional definition)'
+HOVER_MULTI_PROTOTYPE =
+'({} prototypes)'
+HOVER_STRING_BYTES =
+'{} bytes'
+HOVER_STRING_CHARACTERS =
+'{} bytes, {} characters'
+HOVER_MULTI_DEF_PROTO =
+'({} definitions, {} prototypes)'
+HOVER_MULTI_PROTO_NOT_FUNC =
+'({} non functional definition)'
-HOVER_USE_LUA_PATH = '(Search path: `{}`)'
-HOVER_EXTENDS = 'Expand to {}'
-HOVER_TABLE_TIME_UP = 'Partial type inference has been disabled for performance reasons.'
-HOVER_WS_LOADING = 'Workspace loading: {} / {}'
+HOVER_USE_LUA_PATH =
+'(Search path: `{}`)'
+HOVER_EXTENDS =
+'Expand to {}'
+HOVER_TABLE_TIME_UP =
+'Partial type inference has been disabled for performance reasons.'
+HOVER_WS_LOADING =
+'Workspace loading: {} / {}'
-ACTION_DISABLE_DIAG = 'Disable diagnostics in the workspace ({}).'
-ACTION_MARK_GLOBAL = 'Mark `{}` as defined global.'
-ACTION_REMOVE_SPACE = 'Clear all postemptive spaces.'
-ACTION_ADD_SEMICOLON = 'Add `;` .'
-ACTION_ADD_BRACKETS = 'Add brackets.'
-ACTION_RUNTIME_VERSION = 'Change runtime version to {} .'
-ACTION_OPEN_LIBRARY = 'Load globals from {} .'
-ACTION_ADD_DO_END = 'Add `do ... end` .'
-ACTION_FIX_LCOMMENT_END = 'Modify to the correct multi-line annotations closing symbol.'
-ACTION_ADD_LCOMMENT_END = 'Close multi-line annotations.'
-ACTION_FIX_C_LONG_COMMENT = 'Modify to Lua multi-line annotations format.'
-ACTION_FIX_LSTRING_END = 'Modify to the correct long string closing symbol.'
-ACTION_ADD_LSTRING_END = 'Close long string.'
-ACTION_FIX_ASSIGN_AS_EQ = 'Modify to `=` .'
-ACTION_FIX_EQ_AS_ASSIGN = 'Modify to `==` .'
-ACTION_FIX_UEQ = 'Modify to `~=` .'
-ACTION_FIX_THEN_AS_DO = 'Modify to `then` .'
-ACTION_FIX_DO_AS_THEN = 'Modify to `do` .'
-ACTION_ADD_END = 'Add `end` (infer the addition location ny indentations).'
-ACTION_FIX_COMMENT_PREFIX = 'Modify to `--` .'
-ACTION_FIX_NONSTANDARD_SYMBOL = 'Modify to `{symbol}` .'
-ACTION_RUNTIME_UNICODE_NAME = 'Allow Unicode characters.'
-ACTION_SWAP_PARAMS = 'Change to parameter {index} of `{node}`'
-ACTION_FIX_INSERT_SPACE = 'Insert space.'
-ACTION_JSON_TO_LUA = 'Convert JSON to Lua'
-ACTION_DISABLE_DIAG_LINE= 'Disable diagnostics on this line ({}).'
-ACTION_DISABLE_DIAG_FILE= 'Disable diagnostics in this file ({}).'
-ACTION_MARK_ASYNC = 'Mark current function as async.'
+ACTION_DISABLE_DIAG =
+'Disable diagnostics in the workspace ({}).'
+ACTION_MARK_GLOBAL =
+'Mark `{}` as defined global.'
+ACTION_REMOVE_SPACE =
+'Clear all postemptive spaces.'
+ACTION_ADD_SEMICOLON =
+'Add `;` .'
+ACTION_ADD_BRACKETS =
+'Add brackets.'
+ACTION_RUNTIME_VERSION =
+'Change runtime version to {} .'
+ACTION_OPEN_LIBRARY =
+'Load globals from {} .'
+ACTION_ADD_DO_END =
+'Add `do ... end` .'
+ACTION_FIX_LCOMMENT_END =
+'Modify to the correct multi-line annotations closing symbol.'
+ACTION_ADD_LCOMMENT_END =
+'Close multi-line annotations.'
+ACTION_FIX_C_LONG_COMMENT =
+'Modify to Lua multi-line annotations format.'
+ACTION_FIX_LSTRING_END =
+'Modify to the correct long string closing symbol.'
+ACTION_ADD_LSTRING_END =
+'Close long string.'
+ACTION_FIX_ASSIGN_AS_EQ =
+'Modify to `=` .'
+ACTION_FIX_EQ_AS_ASSIGN =
+'Modify to `==` .'
+ACTION_FIX_UEQ =
+'Modify to `~=` .'
+ACTION_FIX_THEN_AS_DO =
+'Modify to `then` .'
+ACTION_FIX_DO_AS_THEN =
+'Modify to `do` .'
+ACTION_ADD_END =
+'Add `end` (infer the addition location ny indentations).'
+ACTION_FIX_COMMENT_PREFIX =
+'Modify to `--` .'
+ACTION_FIX_NONSTANDARD_SYMBOL =
+'Modify to `{symbol}` .'
+ACTION_RUNTIME_UNICODE_NAME =
+'Allow Unicode characters.'
+ACTION_SWAP_PARAMS =
+'Change to parameter {index} of `{node}`'
+ACTION_FIX_INSERT_SPACE =
+'Insert space.'
+ACTION_JSON_TO_LUA =
+'Convert JSON to Lua'
+ACTION_DISABLE_DIAG_LINE=
+'Disable diagnostics on this line ({}).'
+ACTION_DISABLE_DIAG_FILE=
+'Disable diagnostics in this file ({}).'
+ACTION_MARK_ASYNC =
+'Mark current function as async.'
-COMMAND_DISABLE_DIAG = 'Disable diagnostics'
-COMMAND_MARK_GLOBAL = 'Mark defined global'
-COMMAND_REMOVE_SPACE = 'Clear all postemptive spaces'
-COMMAND_ADD_BRACKETS = 'Add brackets'
-COMMAND_RUNTIME_VERSION = 'Change runtime version'
-COMMAND_OPEN_LIBRARY = 'Load globals from 3rd library'
-COMMAND_UNICODE_NAME = 'Allow Unicode characters.'
-COMMAND_JSON_TO_LUA = 'Convert JSON to Lua'
-COMMAND_JSON_TO_LUA_FAILED = 'Convert JSON to Lua failed: {}'
+COMMAND_DISABLE_DIAG =
+'Disable diagnostics'
+COMMAND_MARK_GLOBAL =
+'Mark defined global'
+COMMAND_REMOVE_SPACE =
+'Clear all postemptive spaces'
+COMMAND_ADD_BRACKETS =
+'Add brackets'
+COMMAND_RUNTIME_VERSION =
+'Change runtime version'
+COMMAND_OPEN_LIBRARY =
+'Load globals from 3rd library'
+COMMAND_UNICODE_NAME =
+'Allow Unicode characters.'
+COMMAND_JSON_TO_LUA =
+'Convert JSON to Lua'
+COMMAND_JSON_TO_LUA_FAILED =
+'Convert JSON to Lua failed: {}'
-COMPLETION_IMPORT_FROM = 'Import from {}'
-COMPLETION_DISABLE_AUTO_REQUIRE = 'Disable auto require'
-COMPLETION_ASK_AUTO_REQUIRE = 'Add the code at the top of the file to require this file?'
+COMPLETION_IMPORT_FROM =
+'Import from {}'
+COMPLETION_DISABLE_AUTO_REQUIRE =
+'Disable auto require'
+COMPLETION_ASK_AUTO_REQUIRE =
+'Add the code at the top of the file to require this file?'
-DEBUG_MEMORY_LEAK = "{} I'm sorry for the serious memory leak. The language service will be restarted soon."
-DEBUG_RESTART_NOW = 'Restart now'
+DEBUG_MEMORY_LEAK =
+"{} I'm sorry for the serious memory leak. The language service will be restarted soon."
+DEBUG_RESTART_NOW =
+'Restart now'
-WINDOW_COMPILING = 'Compiling'
-WINDOW_DIAGNOSING = 'Diagnosing'
-WINDOW_INITIALIZING = 'Initializing...'
-WINDOW_PROCESSING_HOVER = 'Processing hover...'
-WINDOW_PROCESSING_DEFINITION = 'Processing definition...'
-WINDOW_PROCESSING_REFERENCE = 'Processing reference...'
-WINDOW_PROCESSING_RENAME = 'Processing rename...'
-WINDOW_PROCESSING_COMPLETION = 'Processing completion...'
-WINDOW_PROCESSING_SIGNATURE = 'Processing signature help...'
-WINDOW_PROCESSING_SYMBOL = 'Processing file symbols...'
-WINDOW_PROCESSING_WS_SYMBOL = 'Processing workspace symbols...'
-WINDOW_PROCESSING_SEMANTIC_FULL = 'Processing full semantic tokens...'
-WINDOW_PROCESSING_SEMANTIC_RANGE = 'Processing incremental semantic tokens...'
-WINDOW_PROCESSING_TYPE_HINT = 'Processing inline hint...'
-WINDOW_INCREASE_UPPER_LIMIT = 'Increase upper limit'
-WINDOW_CLOSE = 'Close'
-WINDOW_SETTING_WS_DIAGNOSTIC = 'You can delay or disable workspace diagnostics in settings'
-WINDOW_DONT_SHOW_AGAIN = "Don't show again"
-WINDOW_DELAY_WS_DIAGNOSTIC = 'Idle time diagnosis (delay {} seconds)'
-WINDOW_DISABLE_DIAGNOSTIC = 'Disable workspace diagnostics'
-WINDOW_LUA_STATUS_WORKSPACE = 'Workspace : {}'
-WINDOW_LUA_STATUS_CACHED_FILES = 'Cached files: {ast}/{max}'
-WINDOW_LUA_STATUS_MEMORY_COUNT = 'Memory usage: {mem:.f}M'
-WINDOW_APPLY_SETTING = 'Apply setting'
-WINDOW_CHECK_SEMANTIC = 'If you are using the color theme in the market, you may need to modify `editor.semanticHighlighting.enabled` to `true` to make semantic tokens take effect.'
-WINDOW_TELEMETRY_HINT = 'Please allow sending anonymous usage data and error reports to help us further improve this extension. Read our privacy policy [here](https://github.com/sumneko/lua-language-server/wiki/Privacy-Policy) .'
-WINDOW_TELEMETRY_ENABLE = 'Allow'
-WINDOW_TELEMETRY_DISABLE = 'Prohibit'
-WINDOW_CLIENT_NOT_SUPPORT_CONFIG = 'Your client does not support modifying settings from the server side, please manually modify the following settings:'
-WINDOW_LCONFIG_NOT_SUPPORT_CONFIG= 'Automatic modification of local settings is not currently supported, please manually modify the following settings:'
-WINDOW_MANUAL_CONFIG_ADD = '`{key}`: add element `{value:q}` ;'
-WINDOW_MANUAL_CONFIG_SET = '`{key}`: set to `{value:q}` ;'
-WINDOW_MANUAL_CONFIG_PROP = '`{key}`: set the property `{prop}` to `{value:q}`;'
-WINDOW_APPLY_WHIT_SETTING = 'Apply and modify settings'
-WINDOW_APPLY_WHITOUT_SETTING = 'Apply but do not modify settings'
-WINDOW_ASK_APPLY_LIBRARY = 'Do you need to configure your work environment as `{}`?'
+WINDOW_COMPILING =
+'Compiling'
+WINDOW_DIAGNOSING =
+'Diagnosing'
+WINDOW_INITIALIZING =
+'Initializing...'
+WINDOW_PROCESSING_HOVER =
+'Processing hover...'
+WINDOW_PROCESSING_DEFINITION =
+'Processing definition...'
+WINDOW_PROCESSING_REFERENCE =
+'Processing reference...'
+WINDOW_PROCESSING_RENAME =
+'Processing rename...'
+WINDOW_PROCESSING_COMPLETION =
+'Processing completion...'
+WINDOW_PROCESSING_SIGNATURE =
+'Processing signature help...'
+WINDOW_PROCESSING_SYMBOL =
+'Processing file symbols...'
+WINDOW_PROCESSING_WS_SYMBOL =
+'Processing workspace symbols...'
+WINDOW_PROCESSING_SEMANTIC_FULL =
+'Processing full semantic tokens...'
+WINDOW_PROCESSING_SEMANTIC_RANGE =
+'Processing incremental semantic tokens...'
+WINDOW_PROCESSING_TYPE_HINT =
+'Processing inline hint...'
+WINDOW_INCREASE_UPPER_LIMIT =
+'Increase upper limit'
+WINDOW_CLOSE =
+'Close'
+WINDOW_SETTING_WS_DIAGNOSTIC =
+'You can delay or disable workspace diagnostics in settings'
+WINDOW_DONT_SHOW_AGAIN =
+"Don't show again"
+WINDOW_DELAY_WS_DIAGNOSTIC =
+'Idle time diagnosis (delay {} seconds)'
+WINDOW_DISABLE_DIAGNOSTIC =
+'Disable workspace diagnostics'
+WINDOW_LUA_STATUS_WORKSPACE =
+'Workspace : {}'
+WINDOW_LUA_STATUS_CACHED_FILES =
+'Cached files: {ast}/{max}'
+WINDOW_LUA_STATUS_MEMORY_COUNT =
+'Memory usage: {mem:.f}M'
+WINDOW_APPLY_SETTING =
+'Apply setting'
+WINDOW_CHECK_SEMANTIC =
+'If you are using the color theme in the market, you may need to modify `editor.semanticHighlighting.enabled` to `true` to make semantic tokens take effect.'
+WINDOW_TELEMETRY_HINT =
+'Please allow sending anonymous usage data and error reports to help us further improve this extension. Read our privacy policy [here](https://github.com/sumneko/lua-language-server/wiki/Privacy-Policy) .'
+WINDOW_TELEMETRY_ENABLE =
+'Allow'
+WINDOW_TELEMETRY_DISABLE =
+'Prohibit'
+WINDOW_CLIENT_NOT_SUPPORT_CONFIG =
+'Your client does not support modifying settings from the server side, please manually modify the following settings:'
+WINDOW_LCONFIG_NOT_SUPPORT_CONFIG=
+'Automatic modification of local settings is not currently supported, please manually modify the following settings:'
+WINDOW_MANUAL_CONFIG_ADD =
+'`{key}`: add element `{value:q}` ;'
+WINDOW_MANUAL_CONFIG_SET =
+'`{key}`: set to `{value:q}` ;'
+WINDOW_MANUAL_CONFIG_PROP =
+'`{key}`: set the property `{prop}` to `{value:q}`;'
+WINDOW_APPLY_WHIT_SETTING =
+'Apply and modify settings'
+WINDOW_APPLY_WHITOUT_SETTING =
+'Apply but do not modify settings'
+WINDOW_ASK_APPLY_LIBRARY =
+'Do you need to configure your work environment as `{}`?'
-CONFIG_LOAD_FAILED = 'Unable to read the settings file: {}'
-CONFIG_LOAD_ERROR = 'Setting file loading error: {}'
-CONFIG_TYPE_ERROR = 'The setting file must be in lua or json format: {}'
+CONFIG_LOAD_FAILED =
+'Unable to read the settings file: {}'
+CONFIG_LOAD_ERROR =
+'Setting file loading error: {}'
+CONFIG_TYPE_ERROR =
+'The setting file must be in lua or json format: {}'
-PLUGIN_RUNTIME_ERROR = [[
+PLUGIN_RUNTIME_ERROR =
+[[
An error occurred in the plugin, please report it to the plugin author.
Please check the details in the output or log.
Plugin path: {}
]]
-PLUGIN_TRUST_LOAD = [[
+PLUGIN_TRUST_LOAD =
+[[
The current settings try to load the plugin at this location:{}
Note that malicious plugin may harm your computer
]]
-PLUGIN_TRUST_YES = [[
+PLUGIN_TRUST_YES =
+[[
Trust and load this plugin
]]
-PLUGIN_TRUST_NO = [[
+PLUGIN_TRUST_NO =
+[[
Don't load this plugin
]]
diff --git a/locale/en-us/setting.lua b/locale/en-us/setting.lua
index 470bb21b..28cfdb64 100644
--- a/locale/en-us/setting.lua
+++ b/locale/en-us/setting.lua
@@ -1,14 +1,18 @@
---@diagnostic disable: undefined-global
-config.runtime.version = "Lua runtime version."
-config.runtime.path = [[
+config.runtime.version =
+"Lua runtime version."
+config.runtime.path =
+[[
When using `require`, how to find the file based on the input name.
Setting this config to `?/init.lua` means that when you enter `require 'myfile'`, `${workspace}/myfile/init.lua` will be searched from the loaded files.
if `runtime.pathStrict` is `false`, `${workspace}/**/myfile/init.lua` will also be searched.
If you want to load files outside the workspace, you need to set `Lua.workspace.library` first.
]]
-config.runtime.pathStrict = 'When enabled, `runtime.path` will only search the first level of directories, see the description of `runtime.path`.'
-config.runtime.special = [[The custom global variables are regarded as some special built-in variables, and the language server will provide special support
+config.runtime.pathStrict =
+'When enabled, `runtime.path` will only search the first level of directories, see the description of `runtime.path`.'
+config.runtime.special =
+[[The custom global variables are regarded as some special built-in variables, and the language server will provide special support
The following example shows that 'include' is treated as' require '.
```json
"Lua.runtime.special" : {
@@ -16,40 +20,64 @@ The following example shows that 'include' is treated as' require '.
}
```
]]
-config.runtime.unicodeName = "Allows Unicode characters in name."
-config.runtime.nonstandardSymbol = "Supports non-standard symbols. Make sure that your runtime environment supports these symbols."
-config.runtime.plugin = "Plugin path. Please read [wiki](https://github.com/sumneko/lua-language-server/wiki/Plugin) to learn more."
-config.runtime.fileEncoding = "File encoding. The `ansi` option is only available under the `Windows` platform."
-config.runtime.builtin = [[
+config.runtime.unicodeName =
+"Allows Unicode characters in name."
+config.runtime.nonstandardSymbol =
+"Supports non-standard symbols. Make sure that your runtime environment supports these symbols."
+config.runtime.plugin =
+"Plugin path. Please read [wiki](https://github.com/sumneko/lua-language-server/wiki/Plugin) to learn more."
+config.runtime.fileEncoding =
+"File encoding. The `ansi` option is only available under the `Windows` platform."
+config.runtime.builtin =
+[[
Adjust the enabled state of the built-in library. You can disable (or redefine) the non-existent library according to the actual runtime environment.
* `default`: Indicates that the library will be enabled or disabled according to the runtime version
* `enable`: always enable
* `disable`: always disable
]]
-config.diagnostics.enable = "Enable diagnostics."
-config.diagnostics.disable = "Disabled diagnostic (Use code in hover brackets)."
-config.diagnostics.globals = "Defined global variables."
-config.diagnostics.severity = "Modified diagnostic severity."
-config.diagnostics.neededFileStatus = [[
+config.diagnostics.enable =
+"Enable diagnostics."
+config.diagnostics.disable =
+"Disabled diagnostic (Use code in hover brackets)."
+config.diagnostics.globals =
+"Defined global variables."
+config.diagnostics.severity =
+"Modified diagnostic severity."
+config.diagnostics.neededFileStatus =
+[[
* Opened: only diagnose opened files
* Any: diagnose all files
* Disable: disable this diagnostic
]]
-config.diagnostics.workspaceDelay = "Latency (milliseconds) for workspace diagnostics. When you start the workspace, or edit any file, the entire workspace will be re-diagnosed in the background. Set to negative to disable workspace diagnostics."
-config.diagnostics.workspaceRate = "Workspace diagnostics run rate (%). Decreasing this value reduces CPU usage, but also reduces the speed of workspace diagnostics. The diagnosis of the file you are currently editing is always done at full speed and is not affected by this setting."
-config.diagnostics.libraryFiles = "How to diagnose files loaded via `Lua.workspace.library`."
-config.diagnostics.ignoredFiles = "How to diagnose ignored files."
-config.diagnostics.files.Enable = "Always diagnose these files."
-config.diagnostics.files.Opened = "Only when these files are opened will it be diagnosed."
-config.diagnostics.files.Disable = "These files are not diagnosed."
-config.workspace.ignoreDir = "Ignored files and directories (Use `.gitignore` grammar)."-- .. example.ignoreDir,
-config.workspace.ignoreSubmodules = "Ignore submodules."
-config.workspace.useGitIgnore = "Ignore files list in `.gitignore` ."
-config.workspace.maxPreload = "Max preloaded files."
-config.workspace.preloadFileSize = "Skip files larger than this value (KB) when preloading."
-config.workspace.library = "In addition to the current workspace, which directories will load files from. The files in these directories will be treated as externally provided code libraries, and some features (such as renaming fields) will not modify these files."
-config.workspace.checkThirdParty = [[
+config.diagnostics.workspaceDelay =
+"Latency (milliseconds) for workspace diagnostics. When you start the workspace, or edit any file, the entire workspace will be re-diagnosed in the background. Set to negative to disable workspace diagnostics."
+config.diagnostics.workspaceRate =
+"Workspace diagnostics run rate (%). Decreasing this value reduces CPU usage, but also reduces the speed of workspace diagnostics. The diagnosis of the file you are currently editing is always done at full speed and is not affected by this setting."
+config.diagnostics.libraryFiles =
+"How to diagnose files loaded via `Lua.workspace.library`."
+config.diagnostics.ignoredFiles =
+"How to diagnose ignored files."
+config.diagnostics.files.Enable =
+"Always diagnose these files."
+config.diagnostics.files.Opened =
+"Only when these files are opened will it be diagnosed."
+config.diagnostics.files.Disable =
+"These files are not diagnosed."
+config.workspace.ignoreDir =
+"Ignored files and directories (Use `.gitignore` grammar)."-- .. example.ignoreDir,
+config.workspace.ignoreSubmodules =
+"Ignore submodules."
+config.workspace.useGitIgnore =
+"Ignore files list in `.gitignore` ."
+config.workspace.maxPreload =
+"Max preloaded files."
+config.workspace.preloadFileSize =
+"Skip files larger than this value (KB) when preloading."
+config.workspace.library =
+"In addition to the current workspace, which directories will load files from. The files in these directories will be treated as externally provided code libraries, and some features (such as renaming fields) will not modify these files."
+config.workspace.checkThirdParty =
+[[
Automatic detection and adaptation of third-party libraries, currently supported libraries are:
* OpenResty
@@ -59,65 +87,127 @@ Automatic detection and adaptation of third-party libraries, currently supported
* skynet
* Jass
]]
-config.workspace.userThirdParty = 'Add private third-party library configuration file paths here, please refer to the built-in [configuration file path](https://github.com/sumneko/lua-language-server/tree/master/meta/3rd)'
-config.completion.enable = 'Enable completion.'
-config.completion.callSnippet = 'Shows function call snippets.'
-config.completion.callSnippet.Disable = "Only shows `function name`."
-config.completion.callSnippet.Both = "Shows `function name` and `call snippet`."
-config.completion.callSnippet.Replace = "Only shows `call snippet.`"
-config.completion.keywordSnippet = 'Shows keyword syntax snippets.'
-config.completion.keywordSnippet.Disable = "Only shows `keyword`."
-config.completion.keywordSnippet.Both = "Shows `keyword` and `syntax snippet`."
-config.completion.keywordSnippet.Replace = "Only shows `syntax snippet`."
-config.completion.displayContext = "Previewing the relevant code snippet of the suggestion may help you understand the usage of the suggestion. The number set indicates the number of intercepted lines in the code fragment. If it is set to `0`, this feature can be disabled."
-config.completion.workspaceWord = "Whether the displayed context word contains the content of other files in the workspace."
-config.completion.showWord = "Show contextual words in suggestions."
-config.completion.showWord.Enable = "Always show context words in suggestions."
-config.completion.showWord.Fallback = "Contextual words are only displayed when suggestions based on semantics cannot be provided."
-config.completion.showWord.Disable = "Do not display context words."
-config.completion.autoRequire = "When the input looks like a file name, automatically `require` this file."
-config.completion.showParams = "Display parameters in completion list. When the function has multiple definitions, they will be displayed separately."
-config.completion.requireSeparator = "The separator used when `require`."
-config.completion.postfix = "The symbol used to trigger the postfix suggestion."
-config.color.mode = "Color mode."
-config.color.mode.Semantic = "Semantic color. You may need to set `editor.semanticHighlighting.enabled` to `true` to take effect."
-config.color.mode.SemanticEnhanced = "Enhanced semantic color. Like `Semantic`, but with additional analysis which might be more computationally expensive."
-config.color.mode.Grammar = "Grammar color."
-config.semantic.enable = "Enable semantic color. You may need to set `editor.semanticHighlighting.enabled` to `true` to take effect."
-config.semantic.variable = "Semantic coloring of variables/fields/parameters."
-config.semantic.annotation = "Semantic coloring of type annotations."
-config.semantic.keyword = "Semantic coloring of keywords/literals/operators. You only need to enable this feature if your editor cannot do syntax coloring."
-config.signatureHelp.enable = "Enable signature help."
-config.hover.enable = "Enable hover."
-config.hover.viewString = "Hover to view the contents of a string (only if the literal contains an escape character)."
-config.hover.viewStringMax = "The maximum length of a hover to view the contents of a string."
-config.hover.viewNumber = "Hover to view numeric content (only if literal is not decimal)."
-config.hover.fieldInfer = "When hovering to view a table, type infer will be performed for each field. When the accumulated time of type infer reaches the set value (MS), the type infer of subsequent fields will be skipped."
-config.hover.previewFields = "When hovering to view a table, limits the maximum number of previews for fields."
-config.hover.enumsLimit = "When the value corresponds to multiple types, limit the number of types displaying."
-config.develop.enable = 'Developer mode. Do not enable, performance will be affected.'
-config.develop.debuggerPort = 'Listen port of debugger.'
-config.develop.debuggerWait = 'Suspend before debugger connects.'
-config.intelliSense.searchDepth = 'Set the search depth for IntelliSense. Increasing this value increases accuracy, but decreases performance. Different workspace have different tolerance for this setting. Please adjust it to the appropriate value.'
-config.intelliSense.fastGlobal = 'In the global variable completion, and view `_G` suspension prompt. This will slightly reduce the accuracy of type speculation, but it will have a significant performance improvement for projects that use a lot of global variables.'
-config.window.statusBar = 'Show extension status in status bar.'
-config.window.progressBar = 'Show progress bar in status bar.'
-config.hint.enable = 'Enable inlay hint.'
-config.hint.paramType = 'Show type hints at the parameter of the function.'
-config.hint.setType = 'Show hints of type at assignment operation.'
-config.hint.paramName = 'Show hints of parameter name at the function call.'
-config.hint.paramName.All = 'All types of parameters are shown.'
-config.hint.paramName.Literal = 'Only literal type parameters are shown.'
-config.hint.paramName.Disable = 'Disable parameter hints.'
-config.hint.arrayIndex = 'Show hints of array index when constructing a table.'
-config.hint.arrayIndex.Enable = 'Show hints in all tables.'
-config.hint.arrayIndex.Auto = 'Show hints only when the table is greater than 3 items, or the table is a mixed table.'
-config.hint.arrayIndex.Disable = 'Disable hints of array index.'
-config.telemetry.enable = [[
+config.workspace.userThirdParty =
+'Add private third-party library configuration file paths here, please refer to the built-in [configuration file path](https://github.com/sumneko/lua-language-server/tree/master/meta/3rd)'
+config.completion.enable =
+'Enable completion.'
+config.completion.callSnippet =
+'Shows function call snippets.'
+config.completion.callSnippet.Disable =
+"Only shows `function name`."
+config.completion.callSnippet.Both =
+"Shows `function name` and `call snippet`."
+config.completion.callSnippet.Replace =
+"Only shows `call snippet.`"
+config.completion.keywordSnippet =
+'Shows keyword syntax snippets.'
+config.completion.keywordSnippet.Disable =
+"Only shows `keyword`."
+config.completion.keywordSnippet.Both =
+"Shows `keyword` and `syntax snippet`."
+config.completion.keywordSnippet.Replace =
+"Only shows `syntax snippet`."
+config.completion.displayContext =
+"Previewing the relevant code snippet of the suggestion may help you understand the usage of the suggestion. The number set indicates the number of intercepted lines in the code fragment. If it is set to `0`, this feature can be disabled."
+config.completion.workspaceWord =
+"Whether the displayed context word contains the content of other files in the workspace."
+config.completion.showWord =
+"Show contextual words in suggestions."
+config.completion.showWord.Enable =
+"Always show context words in suggestions."
+config.completion.showWord.Fallback =
+"Contextual words are only displayed when suggestions based on semantics cannot be provided."
+config.completion.showWord.Disable =
+"Do not display context words."
+config.completion.autoRequire =
+"When the input looks like a file name, automatically `require` this file."
+config.completion.showParams =
+"Display parameters in completion list. When the function has multiple definitions, they will be displayed separately."
+config.completion.requireSeparator =
+"The separator used when `require`."
+config.completion.postfix =
+"The symbol used to trigger the postfix suggestion."
+config.color.mode =
+"Color mode."
+config.color.mode.Semantic =
+"Semantic color. You may need to set `editor.semanticHighlighting.enabled` to `true` to take effect."
+config.color.mode.SemanticEnhanced =
+"Enhanced semantic color. Like `Semantic`, but with additional analysis which might be more computationally expensive."
+config.color.mode.Grammar =
+"Grammar color."
+config.semantic.enable =
+"Enable semantic color. You may need to set `editor.semanticHighlighting.enabled` to `true` to take effect."
+config.semantic.variable =
+"Semantic coloring of variables/fields/parameters."
+config.semantic.annotation =
+"Semantic coloring of type annotations."
+config.semantic.keyword =
+"Semantic coloring of keywords/literals/operators. You only need to enable this feature if your editor cannot do syntax coloring."
+config.signatureHelp.enable =
+"Enable signature help."
+config.hover.enable =
+"Enable hover."
+config.hover.viewString =
+"Hover to view the contents of a string (only if the literal contains an escape character)."
+config.hover.viewStringMax =
+"The maximum length of a hover to view the contents of a string."
+config.hover.viewNumber =
+"Hover to view numeric content (only if literal is not decimal)."
+config.hover.fieldInfer =
+"When hovering to view a table, type infer will be performed for each field. When the accumulated time of type infer reaches the set value (MS), the type infer of subsequent fields will be skipped."
+config.hover.previewFields =
+"When hovering to view a table, limits the maximum number of previews for fields."
+config.hover.enumsLimit =
+"When the value corresponds to multiple types, limit the number of types displaying."
+config.develop.enable =
+'Developer mode. Do not enable, performance will be affected.'
+config.develop.debuggerPort =
+'Listen port of debugger.'
+config.develop.debuggerWait =
+'Suspend before debugger connects.'
+config.intelliSense.searchDepth =
+'Set the search depth for IntelliSense. Increasing this value increases accuracy, but decreases performance. Different workspace have different tolerance for this setting. Please adjust it to the appropriate value.'
+config.intelliSense.fastGlobal =
+'In the global variable completion, and view `_G` suspension prompt. This will slightly reduce the accuracy of type speculation, but it will have a significant performance improvement for projects that use a lot of global variables.'
+config.window.statusBar =
+'Show extension status in status bar.'
+config.window.progressBar =
+'Show progress bar in status bar.'
+config.hint.enable =
+'Enable inlay hint.'
+config.hint.paramType =
+'Show type hints at the parameter of the function.'
+config.hint.setType =
+'Show hints of type at assignment operation.'
+config.hint.paramName =
+'Show hints of parameter name at the function call.'
+config.hint.paramName.All =
+'All types of parameters are shown.'
+config.hint.paramName.Literal =
+'Only literal type parameters are shown.'
+config.hint.paramName.Disable =
+'Disable parameter hints.'
+config.hint.arrayIndex =
+'Show hints of array index when constructing a table.'
+config.hint.arrayIndex.Enable =
+'Show hints in all tables.'
+config.hint.arrayIndex.Auto =
+'Show hints only when the table is greater than 3 items, or the table is a mixed table.'
+config.hint.arrayIndex.Disable =
+'Disable hints of array index.'
+config.format.enable =
+'Enable code formatter.'
+config.telemetry.enable =
+[[
Enable telemetry to send your editor information and error logs over the network. Read our privacy policy [here](https://github.com/sumneko/lua-language-server/wiki/Privacy-Policy).
]]
-config.misc.parameters = '[Command line parameters](https://github.com/sumneko/lua-telemetry-server/tree/master/method) when starting the language service in VSCode.'
-config.IntelliSense.traceLocalSet = 'Please read [wiki](https://github.com/sumneko/lua-language-server/wiki/IntelliSense-optional-features) to learn more.'
-config.IntelliSense.traceReturn = 'Please read [wiki](https://github.com/sumneko/lua-language-server/wiki/IntelliSense-optional-features) to learn more.'
-config.IntelliSense.traceBeSetted = 'Please read [wiki](https://github.com/sumneko/lua-language-server/wiki/IntelliSense-optional-features) to learn more.'
-config.IntelliSense.traceFieldInject = 'Please read [wiki](https://github.com/sumneko/lua-language-server/wiki/IntelliSense-optional-features) to learn more.'
+config.misc.parameters =
+'[Command line parameters](https://github.com/sumneko/lua-telemetry-server/tree/master/method) when starting the language service in VSCode.'
+config.IntelliSense.traceLocalSet =
+'Please read [wiki](https://github.com/sumneko/lua-language-server/wiki/IntelliSense-optional-features) to learn more.'
+config.IntelliSense.traceReturn =
+'Please read [wiki](https://github.com/sumneko/lua-language-server/wiki/IntelliSense-optional-features) to learn more.'
+config.IntelliSense.traceBeSetted =
+'Please read [wiki](https://github.com/sumneko/lua-language-server/wiki/IntelliSense-optional-features) to learn more.'
+config.IntelliSense.traceFieldInject =
+'Please read [wiki](https://github.com/sumneko/lua-language-server/wiki/IntelliSense-optional-features) to learn more.'
diff --git a/locale/pt-br/meta.lua b/locale/pt-br/meta.lua
index 79b2e028..ce48e1c3 100644
--- a/locale/pt-br/meta.lua
+++ b/locale/pt-br/meta.lua
@@ -1,55 +1,84 @@
---@diagnostic disable: undefined-global, lowercase-global
-- basic
-arg = 'Argumentos de inicialização para a versão standalone da linguagem Lua.'
-assert = 'Emite um erro se o valor de seu argumento v for falso (i.e., `nil` ou `false`); caso contrário, devolve todos os seus argumentos. Em caso de erro, `message` é o objeto de erro que, quando ausente, por padrão é `"assertion failed!"`'
-cgopt.collect = 'Realiza um ciclo completo de coleta de lixo (i.e., garbage-collection cycle).'
-cgopt.stop = 'Interrompe a execução automática.'
-cgopt.restart = 'Reinicia a execução automática.'
-cgopt.count = 'Retorna, em Kbytes, a quantidade total de memória utilizada pela linguagem Lua.'
-cgopt.step = 'Executa a coleta de lixo (i.e., garbage-collection) em uma única etapa. A quantidade de execuções por etapa é controlada via `arg`.'
-cgopt.setpause = 'Estabelece pausa. Defina via `arg` o intervalo de pausa do coletor de lixo (i.e., garbage-collection).'
-cgopt.setstepmul = 'Estabelece um multiplicador para etapa de coleta de lixo (i.e., garbage-collection). Defina via `arg` o valor multiplicador.'
-cgopt.incremental = 'Altera o modo do coletor para incremental.'
-cgopt.generational = 'Altera o modo do coletor para geracional.'
-cgopt.isrunning = 'Retorna um valor booleano indicando se o coletor de lixo (i.e., garbage-collection) está em execução.'
-collectgarbage = 'Esta função é uma interface genérica para o coletor de lixo (i.e., garbage-collection). Ela executa diferentes funções de acordo com seu primeiro argumento, `opt`.'
-dofile = 'Abre o arquivo fornecido por argumento e executa seu conteúdo como código Lua. Quando chamado sem argumentos, `dofile` executa o conteúdo da entrada padrão (`stdin`). Retorna todos os valores retornados pelo trecho de código contido no arquivo. Em caso de erros, o `dofile` propaga o erro para seu chamador. Ou seja, o `dofile` não funciona em modo protegido.'
-error = [[
+arg =
+'Argumentos de inicialização para a versão standalone da linguagem Lua.'
+assert =
+'Emite um erro se o valor de seu argumento v for falso (i.e., `nil` ou `false`); caso contrário, devolve todos os seus argumentos. Em caso de erro, `message` é o objeto de erro que, quando ausente, por padrão é `"assertion failed!"`'
+cgopt.collect =
+'Realiza um ciclo completo de coleta de lixo (i.e., garbage-collection cycle).'
+cgopt.stop =
+'Interrompe a execução automática.'
+cgopt.restart =
+'Reinicia a execução automática.'
+cgopt.count =
+'Retorna, em Kbytes, a quantidade total de memória utilizada pela linguagem Lua.'
+cgopt.step =
+'Executa a coleta de lixo (i.e., garbage-collection) em uma única etapa. A quantidade de execuções por etapa é controlada via `arg`.'
+cgopt.setpause =
+'Estabelece pausa. Defina via `arg` o intervalo de pausa do coletor de lixo (i.e., garbage-collection).'
+cgopt.setstepmul =
+'Estabelece um multiplicador para etapa de coleta de lixo (i.e., garbage-collection). Defina via `arg` o valor multiplicador.'
+cgopt.incremental =
+'Altera o modo do coletor para incremental.'
+cgopt.generational =
+'Altera o modo do coletor para geracional.'
+cgopt.isrunning =
+'Retorna um valor booleano indicando se o coletor de lixo (i.e., garbage-collection) está em execução.'
+collectgarbage =
+'Esta função é uma interface genérica para o coletor de lixo (i.e., garbage-collection). Ela executa diferentes funções de acordo com seu primeiro argumento, `opt`.'
+dofile =
+'Abre o arquivo fornecido por argumento e executa seu conteúdo como código Lua. Quando chamado sem argumentos, `dofile` executa o conteúdo da entrada padrão (`stdin`). Retorna todos os valores retornados pelo trecho de código contido no arquivo. Em caso de erros, o `dofile` propaga o erro para seu chamador. Ou seja, o `dofile` não funciona em modo protegido.'
+error =
+[[
Termina a última chamada de função protegida e retorna `message` como objeto de `erro`.
Normalmente, o 'erro' adiciona algumas informações sobre a localização do erro no início da mensagem, quando a mensagem for uma string.
]]
-_G = 'Uma variável global (não uma função) que detém o ambiente global (ver §2.2). Lua em si não usa esta variável; mudar seu valor não afeta nenhum ambiente e vice-versa.'
-getfenv = 'Retorna o ambiente atual em uso pela função. O `f` pode ser uma função Lua ou um número que especifica a função naquele nível de pilha.'
-getmetatable = 'Se o objeto não tiver uma metatable, o retorno é `nil`. Mas caso a metatable do objeto tenha um campo `__metatable`, é retornado o valor associado. Caso contrário, retorna a metatable do objeto dado.'
-ipairs = [[
+_G =
+'Uma variável global (não uma função) que detém o ambiente global (ver §2.2). Lua em si não usa esta variável; mudar seu valor não afeta nenhum ambiente e vice-versa.'
+getfenv =
+'Retorna o ambiente atual em uso pela função. O `f` pode ser uma função Lua ou um número que especifica a função naquele nível de pilha.'
+getmetatable =
+'Se o objeto não tiver uma metatable, o retorno é `nil`. Mas caso a metatable do objeto tenha um campo `__metatable`, é retornado o valor associado. Caso contrário, retorna a metatable do objeto dado.'
+ipairs =
+[[
Retorna três valores (uma função iteradora, a tabela `t`, e `0`) para que a seguinte construção
```lua
for i,v in ipairs(t) do body end
```
possa iterar sobre os pares de valor-chave `(1,t[1]), (2,t[2]), ...`, até o primeiro índice ausente.
]]
-loadmode.b = 'Somente blocos binários.'
-loadmode.t = 'Somente blocos de texto.'
-loadmode.bt = 'Tanto binário quanto texto.'
-load['<5.1'] = 'Carrega um bloco utilizando a função `func` para obter suas partes. Cada chamada para o `func` deve retornar uma string que é concatenada com os resultados anteriores.'
-load['>5.2'] = [[
+loadmode.b =
+'Somente blocos binários.'
+loadmode.t =
+'Somente blocos de texto.'
+loadmode.bt =
+'Tanto binário quanto texto.'
+load['<5.1'] =
+'Carrega um bloco utilizando a função `func` para obter suas partes. Cada chamada para o `func` deve retornar uma string que é concatenada com os resultados anteriores.'
+load['>5.2'] =
+[[
Carrega um bloco.
Se o bloco (i.e., `chunk`) é uma string, o bloco é essa string. Se o bloco é uma função, a função "load" é chamada repetidamente para obter suas partes. Cada chamada para o bloco deve retornar uma string que é concatenada com os resultados anteriores. O fim do bloco é sinalizado com o retorno de uma string vazia ou `nil`.
]]
-loadfile = 'Carrega um bloco de arquivo `filename` ou da entrada padrão, se nenhum nome de arquivo for dado.'
-loadstring = 'Carrega um bloco a partir de uma string dada.'
-module = 'Cria um módulo.'
-next = [[
+loadfile =
+'Carrega um bloco de arquivo `filename` ou da entrada padrão, se nenhum nome de arquivo for dado.'
+loadstring =
+'Carrega um bloco a partir de uma string dada.'
+module =
+'Cria um módulo.'
+next =
+[[
Permite que um programa percorra todos os campos de uma tabela. Seu primeiro argumento é uma tabela e seu segundo argumento é um índice nesta tabela. Uma chamada `next` retorna o próximo índice da tabela e seu valor associado. Quando chamado usando `nil` como segundo argumento, `next` retorna um índice inicial e seu valor associado. Quando chamado com o último índice, ou com `nil` em uma tabela vazia, o `next` retorna o `nil`. Se o segundo argumento estiver ausente, então é interpretado como `nil`. Portanto, pode-se utilizar o `next(t)` para verificar se uma tabela está vazia.
A ordem na qual os índices são enumerados não é especificada, *mesmo para índices numéricos*. (Para percorrer uma tabela em ordem numérica, utilize um `for`).
O comportamento do `next` é indefinido se, durante a iteração/travessia, você atribuir qualquer valor a um campo inexistente na tabela. Você pode, entretanto, modificar os campos existentes e pode, inclusive, os definir como nulos.
]]
-pairs = [[
+pairs =
+[[
Se `t` tem um "meta" método (i.e., metamethod) `__pairs`, a chamada é feita usando t como argumento e retorna os três primeiros resultados.
Caso contrário, retorna três valores: a função $next, a tabela `t` e `nil`, para que a seguinte construção
@@ -60,160 +89,246 @@ possa iterar sobre todos os pares de valor-chave da tabela 't'.
Veja a função $next para saber as ressalvas em modificar uma tabela durante sua iteração.
]]
-pcall = [[
+pcall =
+[[
Chama a função `f` com os argumentos dados em modo *protegido*. Isto significa que qualquer erro dentro de `f` não é propagado; em vez disso, o `pcall` captura o erro e retorna um código de status. Seu primeiro resultado é o código de status (booleano), que é verdadeiro se a chamada for bem sucedida sem erros. Neste caso, `pcall' também retorna todos os resultados da chamada, após este primeiro resultado. Em caso de qualquer erro, `pcall` retorna `false` mais o objeto de erro.
]]
-print = [[
+print =
+[[
Recebe qualquer número de argumentos e imprime seus valores na saída padrão `stdout`, convertendo cada argumento em uma string seguindo as mesmas regras do $tostring.
A função `print` não é destinada à saída formatada, mas apenas como uma forma rápida de mostrar um valor, por exemplo, para debugging. Para controle completo sobre a saída, use $string.format e $io.write.
]]
-rawequal = 'Verifica se v1 é igual a v2, sem invocar a metatable `__eq`.'
-rawget = 'Obtém o valor real de `table[index]`, sem invocar a metatable `__index`.'
-rawlen = 'Retorna o comprimento do objeto `v`, sem invocar a metatable `__len`.'
-rawset = [[
+rawequal =
+'Verifica se v1 é igual a v2, sem invocar a metatable `__eq`.'
+rawget =
+'Obtém o valor real de `table[index]`, sem invocar a metatable `__index`.'
+rawlen =
+'Retorna o comprimento do objeto `v`, sem invocar a metatable `__len`.'
+rawset =
+[[
Define o valor real de `table[index]` para `value`, sem utilizar o metavalue `__newindex`. `table` deve ser uma tabela, `index` qualquer valor diferente de `nil` e `NaN`, e `value` qualquer valor de tipos do Lua.
Esta função retorna uma `table`.
]]
-select = 'Se `index` é um número, retorna todos os argumentos após o número do argumento `index`; um número negativo de índices do final (`-1` é o último argumento). Caso contrário, `index` deve ser a string `"#"`, e `select` retorna o número total de argumentos extras dados.'
-setfenv = 'Define o ambiente a ser utilizado pela função em questão.'
-setmetatable = [[
+select =
+'Se `index` é um número, retorna todos os argumentos após o número do argumento `index`; um número negativo de índices do final (`-1` é o último argumento). Caso contrário, `index` deve ser a string `"#"`, e `select` retorna o número total de argumentos extras dados.'
+setfenv =
+'Define o ambiente a ser utilizado pela função em questão.'
+setmetatable =
+[[
Define a metatable para a tabela dada. Se `metatabela` for `nil`, remove a metatable da tabela em questão. Se a metatable original tiver um campo `__metatable', um erro é lançado.
Esta função retorna uma `table`.
Para alterar a metatable de outros tipos do código Lua, você deve utilizar a biblioteca de debugging (§6.10).
]]
-tonumber = [[
+tonumber =
+[[
Quando chamado sem a base, `tonumber` tenta converter seu argumento para um número. Se o argumento já for um número ou uma string numérica, então `tonumber` retorna este número; caso contrário, retorna `fail`.
A conversão de strings pode resultar em números inteiros ou de ponto flutuante, de acordo com as convenções lexicais de Lua (ver §3.1). A string pode ter espaços antes e depois e um sinal.
]]
-tostring = [[
+tostring =
+[[
Recebe um valor de qualquer tipo e o converte em uma string em formato legível por humanos.
Se a metatable de `v` tem um campo `__tostring', então `tostring' chama o valor correspondente usando `v` como argumento, e utiliza o resultado da chamada como seu resultado. Caso contrário, se a metatable de `v` tiver um campo `__name` com um valor do tipo string, `tostring` pode utilizar essa string em seu resultado final.
Para controle completo de como os números são convertidos, utilize $string.format.
]]
-type = [[
+type =
+[[
Retorna o tipo de seu único argumento, codificado como uma string. Os resultados possíveis desta função são `"nil"` (uma string, não o valor `nil`), `"number"`, `"string"`, `"boolean"`, `"table"`, `"function"`, `"thread"`, e `"userdata"`.
]]
-_VERSION = 'Uma variável global (não uma função) que contém uma string contendo a versão Lua em execução.'
-warn = 'Emite um aviso com uma mensagem composta pela concatenação de todos os seus argumentos (que devem ser strings).'
-xpcall['=5.1'] = 'Faz chamada a função `f` com os argumentos dados e em modo protegido, usando um manipulador de mensagens dado.'
-xpcall['>5.2'] = 'Faz chamada a função `f` com os argumentos dados e em modo protegido, usando um manipulador de mensagens dado.'
-unpack = [[
+_VERSION =
+'Uma variável global (não uma função) que contém uma string contendo a versão Lua em execução.'
+warn =
+'Emite um aviso com uma mensagem composta pela concatenação de todos os seus argumentos (que devem ser strings).'
+xpcall['=5.1'] =
+'Faz chamada a função `f` com os argumentos dados e em modo protegido, usando um manipulador de mensagens dado.'
+xpcall['>5.2'] =
+'Faz chamada a função `f` com os argumentos dados e em modo protegido, usando um manipulador de mensagens dado.'
+unpack =
+[[
Retorna os elementos da lista dada. Esta função é equivalente a
```lua
return list[i], list[i+1], ···, list[j]
```
]]
-bit32 = ''
-bit32.arshift = [[
+bit32 =
+''
+bit32.arshift =
+[[
Retorna o número `x` deslocado `disp` bits para a direita. Deslocamentos negativos movem os bits para a esquerda.
Esta operação de deslocamento é chamada de deslocamento aritmético. Os bits vagos à esquerda são preenchidos com cópias do bit mais significativo de `x`; os bits vagos à direita são preenchidos com zeros.
]]
-bit32.band = 'Retorna a operação bitwise *and* de seus operandos.'
-bit32.bnot = [[
+bit32.band =
+'Retorna a operação bitwise *and* de seus operandos.'
+bit32.bnot =
+[[
Retorna a negação da operação bitwise de `x`.
```lua
-assert(bit32.bnot(x) == (-1 - x) % 2^32)
+assert(bit32.bnot(x) ==
+(-1 - x) % 2^32)
```
]]
-bit32.bor = 'Retorna a operação bitwise *or* de seus operandos.'
-bit32.btest = 'Retorna um valor booleano verdadeiro se a operação bitwise *and* de seus operandos for diferente de zero. Falso, caso contrário.'
-bit32.bxor = 'Retorna a operação bitwise *exclusive or* de seus operandos.'
-bit32.extract = 'Retorna o número formado pelos bits de `field` a `field + width - 1` de `n`, sem sinal.'
-bit32.replace = 'Retorna uma cópia de `n` com os bits de `field` a `field + width - 1` substituídos pelo valor `v` .'
-bit32.lrotate = 'Retorna o número `x` rotacionado `disp` bits para a esquerda. Rotações negativos movem os bits para a direita. '
-bit32.lshift = [[
+bit32.bor =
+'Retorna a operação bitwise *or* de seus operandos.'
+bit32.btest =
+'Retorna um valor booleano verdadeiro se a operação bitwise *and* de seus operandos for diferente de zero. Falso, caso contrário.'
+bit32.bxor =
+'Retorna a operação bitwise *exclusive or* de seus operandos.'
+bit32.extract =
+'Retorna o número formado pelos bits de `field` a `field + width - 1` de `n`, sem sinal.'
+bit32.replace =
+'Retorna uma cópia de `n` com os bits de `field` a `field + width - 1` substituídos pelo valor `v` .'
+bit32.lrotate =
+'Retorna o número `x` rotacionado `disp` bits para a esquerda. Rotações negativos movem os bits para a direita. '
+bit32.lshift =
+[[
Retorna o número `x` deslocado `disp` bits para a esquerda. Deslocamentos negativos movem os bits para a direita. Em ambas as direções, os bits vazios/vagos são preenchidos com zeros.
```lua
-assert(bit32.lshift(b, disp) == (b * 2^disp) % 2^32)
+assert(bit32.lshift(b, disp) ==
+(b * 2^disp) % 2^32)
```
]]
-bit32.rrotate = 'Retorna o número `x` rotacionado `disp` bits para a direita. Deslocamentos negativos movem os bits para a esquerda.'
-bit32.rshift = [[
+bit32.rrotate =
+'Retorna o número `x` rotacionado `disp` bits para a direita. Deslocamentos negativos movem os bits para a esquerda.'
+bit32.rshift =
+[[
Retorna o número `x` deslocado `disp` bits para a direita. Deslocamentos negativos movem os bits para a esquerda. Em ambas as direções, os bits vazios são preenchidos com zeros.
```lua
-assert(bit32.rshift(b, disp) == math.floor(b % 2^32 / 2^disp))
+assert(bit32.rshift(b, disp) ==
+math.floor(b % 2^32 / 2^disp))
```
]]
-coroutine = ''
-coroutine.create = 'Cria uma nova `coroutine`, a partir de uma função `f` e retorna esta coroutine como objeto do tipo `"thread"`.'
-coroutine.isyieldable = 'Retorna verdadeiro quando a `coroutine` em execução for finalizada.'
-coroutine.isyieldable['>5.4']= 'Retorna verdadeiro quando a `coroutine` `co` for finalizada. Por padrão `co` é uma coroutine em execução.'
-coroutine.close = 'Finaliza a coroutine `co` , encerrando todas as variáveis pendentes e colocando a coroutine em um estado morto.'
-coroutine.resume = 'Inicia ou continua a execução da coroutine `co`.'
-coroutine.running = 'Retorna a `coroutine` corrente e um booleana verdadeiro quando a coroutine corrente é a principal.'
-coroutine.status = 'Retorna o status da `coroutine `co`.'
-coroutine.wrap = 'Cria uma nova `coroutine`, a partir de uma função `f` e retorna uma função que retorna a coroutine cada vez que ele é chamado.'
-coroutine.yield = 'Suspende a execução da coroutine chamada.'
-costatus.running = 'Está em execução.'
-costatus.suspended = 'Está suspenso ou não foi iniciado.'
-costatus.normal = 'Está ativo, mas não está em execução.'
-costatus.dead = 'Terminou ou parou devido a erro'
+coroutine =
+''
+coroutine.create =
+'Cria uma nova `coroutine`, a partir de uma função `f` e retorna esta coroutine como objeto do tipo `"thread"`.'
+coroutine.isyieldable =
+'Retorna verdadeiro quando a `coroutine` em execução for finalizada.'
+coroutine.isyieldable['>5.4']=
+'Retorna verdadeiro quando a `coroutine` `co` for finalizada. Por padrão `co` é uma coroutine em execução.'
+coroutine.close =
+'Finaliza a coroutine `co` , encerrando todas as variáveis pendentes e colocando a coroutine em um estado morto.'
+coroutine.resume =
+'Inicia ou continua a execução da coroutine `co`.'
+coroutine.running =
+'Retorna a `coroutine` corrente e um booleana verdadeiro quando a coroutine corrente é a principal.'
+coroutine.status =
+'Retorna o status da `coroutine `co`.'
+coroutine.wrap =
+'Cria uma nova `coroutine`, a partir de uma função `f` e retorna uma função que retorna a coroutine cada vez que ele é chamado.'
+coroutine.yield =
+'Suspende a execução da coroutine chamada.'
+costatus.running =
+'Está em execução.'
+costatus.suspended =
+'Está suspenso ou não foi iniciado.'
+costatus.normal =
+'Está ativo, mas não está em execução.'
+costatus.dead =
+'Terminou ou parou devido a erro'
-debug = ''
-debug.debug = 'Entra em modo interativo com o usuário, executando os comandos de entrada.'
-debug.getfenv = 'Retorna o ambiente do objeto `o` .'
-debug.gethook = 'Retorna as configurações do `hook` atual da `thread`.'
-debug.getinfo = 'Retorna uma tabela com informações sobre uma função.'
-debug.getlocal['<5.1'] = 'Retorna o nome e o valor da variável local com índice `local` da função de nível `level` da pilha.'
-debug.getlocal['>5.2'] = 'Retorna o nome e o valor da variável local com índice `local` da função de nível `f` da pilha.'
-debug.getmetatable = 'Retorna a `metatable` do valor dado.'
-debug.getregistry = 'Retorna a tabela de registro.'
-debug.getupvalue = 'Retorna o nome e o valor da variável antecedente com índice `up` da função.'
-debug.getuservalue['<5.3'] = 'Retorna o valor de Lua associado a `u` (i.e., user).'
-debug.getuservalue['>5.4'] = [[
+debug =
+''
+debug.debug =
+'Entra em modo interativo com o usuário, executando os comandos de entrada.'
+debug.getfenv =
+'Retorna o ambiente do objeto `o` .'
+debug.gethook =
+'Retorna as configurações do `hook` atual da `thread`.'
+debug.getinfo =
+'Retorna uma tabela com informações sobre uma função.'
+debug.getlocal['<5.1'] =
+'Retorna o nome e o valor da variável local com índice `local` da função de nível `level` da pilha.'
+debug.getlocal['>5.2'] =
+'Retorna o nome e o valor da variável local com índice `local` da função de nível `f` da pilha.'
+debug.getmetatable =
+'Retorna a `metatable` do valor dado.'
+debug.getregistry =
+'Retorna a tabela de registro.'
+debug.getupvalue =
+'Retorna o nome e o valor da variável antecedente com índice `up` da função.'
+debug.getuservalue['<5.3'] =
+'Retorna o valor de Lua associado a `u` (i.e., user).'
+debug.getuservalue['>5.4'] =
+[[
Retorna o `n`-ésimo valor de usuário associado
aos dados do usuário `u` e um booleano,
`false`, se nos dados do usuário não existir esse valor.
]]
-debug.setcstacklimit = [[
+debug.setcstacklimit =
+[[
### **Deprecated in `Lua 5.4.2`**
Estabelece um novo limite para a pilha C. Este limite controla quão profundamente as chamadas aninhadas podem ir em Lua, com a intenção de evitar um transbordamento da pilha.
Em caso de sucesso, esta função retorna o antigo limite. Em caso de erro, ela retorna `false`.
]]
-debug.setfenv = 'Define o ambiente do `object` dado para a `table` dada .'
-debug.sethook = 'Define a função dada como um `hook`.'
-debug.setlocal = 'Atribui o valor `value` à variável local com índice `local` da função de nível `level` da pilha.'
-debug.setmetatable = 'Define a `metatable` com o valor dado para tabela dada (que pode ser `nil`).'
-debug.setupvalue = 'Atribui `value` a variável antecedente com índice `up` da função.'
-debug.setuservalue['<5.3'] = 'Define o valor dado como o valor Lua associado ao `udata` (i.e., user data).'
-debug.setuservalue['>5.4'] = [[
+debug.setfenv =
+'Define o ambiente do `object` dado para a `table` dada .'
+debug.sethook =
+'Define a função dada como um `hook`.'
+debug.setlocal =
+'Atribui o valor `value` à variável local com índice `local` da função de nível `level` da pilha.'
+debug.setmetatable =
+'Define a `metatable` com o valor dado para tabela dada (que pode ser `nil`).'
+debug.setupvalue =
+'Atribui `value` a variável antecedente com índice `up` da função.'
+debug.setuservalue['<5.3'] =
+'Define o valor dado como o valor Lua associado ao `udata` (i.e., user data).'
+debug.setuservalue['>5.4'] =
+[[
Define o valor dado como
o `n`-ésimo valor de usuário associado ao `udata` (i.e., user data).
O `udata` deve ser um dado de usuário completo.
]]
-debug.traceback = 'Retorna uma string com um `traceback` de chamadas. A string de mensagen (opcional) é anexada no início do traceback.'
-debug.upvalueid = 'Retorna um identificador único (como um dado de usuário leve) para o valor antecedente de numero `n` da função dada.'
-debug.upvaluejoin = 'Faz o `n1`-ésimo valor da função `f1` (i.e., closure Lua) referir-se ao `n2`-ésimo valor da função `f2`.'
-infowhat.n = '`name` e `namewhat`'
-infowhat.S = '`source`, `short_src`, `linedefined`, `lastlinedefined` e `what`'
-infowhat.l = '`currentline`'
-infowhat.t = '`istailcall`'
-infowhat.u['<5.1'] = '`nups`'
-infowhat.u['>5.2'] = '`nups`, `nparams` e `isvararg`'
-infowhat.f = '`func`'
-infowhat.r = '`ftransfer` e `ntransfer`'
-infowhat.L = '`activelines`'
-hookmask.c = 'Faz chamada a um `hook` quando o Lua chama uma função.'
-hookmask.r = 'Faz chamada a um `hook` quando o retorno de uma função é executado.'
-hookmask.l = 'Faz chamada a um `hook` quando encontra nova linha de código.'
+debug.traceback =
+'Retorna uma string com um `traceback` de chamadas. A string de mensagen (opcional) é anexada no início do traceback.'
+debug.upvalueid =
+'Retorna um identificador único (como um dado de usuário leve) para o valor antecedente de numero `n` da função dada.'
+debug.upvaluejoin =
+'Faz o `n1`-ésimo valor da função `f1` (i.e., closure Lua) referir-se ao `n2`-ésimo valor da função `f2`.'
+infowhat.n =
+'`name` e `namewhat`'
+infowhat.S =
+'`source`, `short_src`, `linedefined`, `lastlinedefined` e `what`'
+infowhat.l =
+'`currentline`'
+infowhat.t =
+'`istailcall`'
+infowhat.u['<5.1'] =
+'`nups`'
+infowhat.u['>5.2'] =
+'`nups`, `nparams` e `isvararg`'
+infowhat.f =
+'`func`'
+infowhat.r =
+'`ftransfer` e `ntransfer`'
+infowhat.L =
+'`activelines`'
+hookmask.c =
+'Faz chamada a um `hook` quando o Lua chama uma função.'
+hookmask.r =
+'Faz chamada a um `hook` quando o retorno de uma função é executado.'
+hookmask.l =
+'Faz chamada a um `hook` quando encontra nova linha de código.'
-file = ''
-file[':close'] = 'Fecha o arquivo `file`.'
-file[':flush'] = 'Salva qualquer dado de entrada no arquivo `file`.'
-file[':lines'] = [[
+file =
+''
+file[':close'] =
+'Fecha o arquivo `file`.'
+file[':flush'] =
+'Salva qualquer dado de entrada no arquivo `file`.'
+file[':lines'] =
+[[
------
```lua
for c in file:lines(...) do
@@ -221,29 +336,51 @@ for c in file:lines(...) do
end
```
]]
-file[':read'] = 'Lê o arquivo de acordo com o formato fornecido e que especifica o que deve ser lido.'
-file[':seek'] = 'Define e obtém a posição do arquivo, medida a partir do início do arquivo.'
-file[':setvbuf'] = 'Define o modo de `buffer` para um arquivo de saída.'
-file[':write'] = 'Escreve o valor de cada um de seus argumentos no arquivo.'
-readmode.n = 'Lê um numeral e o devolve como número.'
-readmode.a = 'Lê o arquivo completo.'
-readmode.l = 'Lê a próxima linha pulando o final da linha.'
-readmode.L = 'Lê a próxima linha mantendo o final da linha.'
-seekwhence.set = 'O cursor base é o início do arquivo.'
-seekwhence.cur = 'O cursor base é a posição atual.'
-seekwhence['.end'] = 'O cursor base é o final do arquivo.'
-vbuf.no = 'A saída da operação aparece imediatamente.'
-vbuf.full = 'Realizado apenas quando o `buffer` está cheio.'
-vbuf.line = '`Buffered` até que uma nova linha seja encontrada.'
+file[':read'] =
+'Lê o arquivo de acordo com o formato fornecido e que especifica o que deve ser lido.'
+file[':seek'] =
+'Define e obtém a posição do arquivo, medida a partir do início do arquivo.'
+file[':setvbuf'] =
+'Define o modo de `buffer` para um arquivo de saída.'
+file[':write'] =
+'Escreve o valor de cada um de seus argumentos no arquivo.'
+readmode.n =
+'Lê um numeral e o devolve como número.'
+readmode.a =
+'Lê o arquivo completo.'
+readmode.l =
+'Lê a próxima linha pulando o final da linha.'
+readmode.L =
+'Lê a próxima linha mantendo o final da linha.'
+seekwhence.set =
+'O cursor base é o início do arquivo.'
+seekwhence.cur =
+'O cursor base é a posição atual.'
+seekwhence['.end'] =
+'O cursor base é o final do arquivo.'
+vbuf.no =
+'A saída da operação aparece imediatamente.'
+vbuf.full =
+'Realizado apenas quando o `buffer` está cheio.'
+vbuf.line =
+'`Buffered` até que uma nova linha seja encontrada.'
-io = ''
-io.stdin = 'Entrada padrão.'
-io.stdout = 'Saída padrão.'
-io.stderr = 'Erro padrão.'
-io.close = 'Fecha o arquivo dado ou o arquivo de saída padrão.'
-io.flush = 'Salva todos os dados gravados no arquivo de saída padrão.'
-io.input = 'Define o arquivo de entrada padrão.'
-io.lines = [[
+io =
+''
+io.stdin =
+'Entrada padrão.'
+io.stdout =
+'Saída padrão.'
+io.stderr =
+'Erro padrão.'
+io.close =
+'Fecha o arquivo dado ou o arquivo de saída padrão.'
+io.flush =
+'Salva todos os dados gravados no arquivo de saída padrão.'
+io.input =
+'Define o arquivo de entrada padrão.'
+io.lines =
+[[
------
```lua
for c in io.lines(filename, ...) do
@@ -251,161 +388,289 @@ for c in io.lines(filename, ...) do
end
```
]]
-io.open = 'Abre um arquivo no modo especificado pela *string* `mode`.'
-io.output = 'Define o arquivo de saída padrão.'
-io.popen = 'Inicia o programa dado em um processo separado.'
-io.read = 'Lê o arquivo de acordo com o formato fornecido e que especifica o que deve ser lido.'
-io.tmpfile = 'Em caso de sucesso, retorna um `handler` para um arquivo temporário.'
-io.type = 'Verifica se `obj` é um identificador de arquivo válido.'
-io.write = 'Escreve o valor de cada um dos seus argumentos para o arquivo de saída padrão.'
-openmode.r = 'Modo de leitura.'
-openmode.w = 'Modo de escrita.'
-openmode.a = 'Modo de anexação.'
-openmode['.r+'] = 'Modo de atualização, todos os dados anteriores são preservados.'
-openmode['.w+'] = 'Modo de atualização, todos os dados anteriores são apagados.'
-openmode['.a+'] = 'Modo de anexação e atualização, os dados anteriores são preservados, a escrita só é permitida no final do arquivo.'
-openmode.rb = 'Modo de leitura. (em modo binário)'
-openmode.wb = 'Modo de escrita. (em modo binário)'
-openmode.ab = 'Modo de anexação. (em modo binário)'
-openmode['.r+b'] = 'Modo de atualização, todos os dados anteriores são preservados. (em modo binário)'
-openmode['.w+b'] = 'Modo de atualização, todos os dados anteriores são apagados. (em modo binário)'
-openmode['.a+b'] = 'Modo de anexação e atualização, todos os dados anteriores são preservados, a escrita só é permitida no final do arquivo. (em modo binário)'
-popenmode.r = 'Leia dados deste programa pelo arquivo.'
-popenmode.w = 'Escreva dados neste programa pelo arquivo.'
-filetype.file = '`handler` para arquivo aberto.'
-filetype['.closed file'] = '`handler` para arquivo fechado.'
-filetype['.nil'] = 'Não é um `handler` de arquivo'
+io.open =
+'Abre um arquivo no modo especificado pela *string* `mode`.'
+io.output =
+'Define o arquivo de saída padrão.'
+io.popen =
+'Inicia o programa dado em um processo separado.'
+io.read =
+'Lê o arquivo de acordo com o formato fornecido e que especifica o que deve ser lido.'
+io.tmpfile =
+'Em caso de sucesso, retorna um `handler` para um arquivo temporário.'
+io.type =
+'Verifica se `obj` é um identificador de arquivo válido.'
+io.write =
+'Escreve o valor de cada um dos seus argumentos para o arquivo de saída padrão.'
+openmode.r =
+'Modo de leitura.'
+openmode.w =
+'Modo de escrita.'
+openmode.a =
+'Modo de anexação.'
+openmode['.r+'] =
+'Modo de atualização, todos os dados anteriores são preservados.'
+openmode['.w+'] =
+'Modo de atualização, todos os dados anteriores são apagados.'
+openmode['.a+'] =
+'Modo de anexação e atualização, os dados anteriores são preservados, a escrita só é permitida no final do arquivo.'
+openmode.rb =
+'Modo de leitura. (em modo binário)'
+openmode.wb =
+'Modo de escrita. (em modo binário)'
+openmode.ab =
+'Modo de anexação. (em modo binário)'
+openmode['.r+b'] =
+'Modo de atualização, todos os dados anteriores são preservados. (em modo binário)'
+openmode['.w+b'] =
+'Modo de atualização, todos os dados anteriores são apagados. (em modo binário)'
+openmode['.a+b'] =
+'Modo de anexação e atualização, todos os dados anteriores são preservados, a escrita só é permitida no final do arquivo. (em modo binário)'
+popenmode.r =
+'Leia dados deste programa pelo arquivo.'
+popenmode.w =
+'Escreva dados neste programa pelo arquivo.'
+filetype.file =
+'`handler` para arquivo aberto.'
+filetype['.closed file'] =
+'`handler` para arquivo fechado.'
+filetype['.nil'] =
+'Não é um `handler` de arquivo'
-math = ''
-math.abs = 'Retorna o valor absoluto de `x`.'
-math.acos = 'Retorna o arco cosseno de `x` (em radianos).'
-math.asin = 'Retorna o arco seno de `x` (em radianos).'
-math.atan['<5.2'] = 'Retorna o arco tangente de `x` (em radianos).'
-math.atan['>5.3'] = 'Retorna o arco tangente de `y/x` (em radianos).'
-math.atan2 = 'Retorna o arco tangente de `y/x` (em radianos).'
-math.ceil = 'Retorna o menor valor inteiro maior ou igual a `x`.'
-math.cos = 'Retorna o cosseno de `x` (requer valor em radianos).'
-math.cosh = 'Retorna o cosseno hiperbólico de `x` (requer valor em radianos).'
-math.deg = 'Converte o ângulo `x` de radianos para graus.'
-math.exp = 'Retorna o valor `e^x` (onde `e` é a base do logaritmo natural).'
-math.floor = 'Retorna o maior valor inteiro menor ou igual a `x`.'
-math.fmod = 'Retorna o resto da divisão de `x` por `y` que arredonda o quociente para zero.'
-math.frexp = 'Decompõe `x` em fatores e expoentes. Retorna `m` e `e` tal que `x = m * (2 ^ e)` é um inteiro e o valor absoluto de `m` está no intervalo [0,5, 1) (ou zero quando `x` é zero).'
-math.huge = 'Um valor maior que qualquer outro valor numérico.'
-math.ldexp = 'Retorna `m * (2 ^ e)`.'
-math.log['<5.1'] = 'Retorna o logaritmo natural de `x`.'
-math.log['>5.2'] = 'Retorna o logaritmo de `x` na base dada.'
-math.log10 = 'Retorna o logaritmo `x` na base 10.'
-math.max = 'Retorna o argumento com o valor máximo de acordo com o operador `<`.'
-math.maxinteger = 'Retorna o valor máximo para um inteiro.'
-math.min = 'Retorna o argumento com o valor mínimo de acordo com o operador `<`.'
-math.mininteger = 'Retorna o valor mínimo para um inteiro.'
-math.modf = 'Retorna a parte inteira e a parte fracionária de `x`.'
-math.pi = 'O valor de *π*.'
-math.pow = 'Retorna `x ^ y`.'
-math.rad = 'Converte o ângulo `x` de graus para radianos.'
-math.random = [[
+math =
+''
+math.abs =
+'Retorna o valor absoluto de `x`.'
+math.acos =
+'Retorna o arco cosseno de `x` (em radianos).'
+math.asin =
+'Retorna o arco seno de `x` (em radianos).'
+math.atan['<5.2'] =
+'Retorna o arco tangente de `x` (em radianos).'
+math.atan['>5.3'] =
+'Retorna o arco tangente de `y/x` (em radianos).'
+math.atan2 =
+'Retorna o arco tangente de `y/x` (em radianos).'
+math.ceil =
+'Retorna o menor valor inteiro maior ou igual a `x`.'
+math.cos =
+'Retorna o cosseno de `x` (requer valor em radianos).'
+math.cosh =
+'Retorna o cosseno hiperbólico de `x` (requer valor em radianos).'
+math.deg =
+'Converte o ângulo `x` de radianos para graus.'
+math.exp =
+'Retorna o valor `e^x` (onde `e` é a base do logaritmo natural).'
+math.floor =
+'Retorna o maior valor inteiro menor ou igual a `x`.'
+math.fmod =
+'Retorna o resto da divisão de `x` por `y` que arredonda o quociente para zero.'
+math.frexp =
+'Decompõe `x` em fatores e expoentes. Retorna `m` e `e` tal que `x = m * (2 ^ e)` é um inteiro e o valor absoluto de `m` está no intervalo [0,5, 1) (ou zero quando `x` é zero).'
+math.huge =
+'Um valor maior que qualquer outro valor numérico.'
+math.ldexp =
+'Retorna `m * (2 ^ e)`.'
+math.log['<5.1'] =
+'Retorna o logaritmo natural de `x`.'
+math.log['>5.2'] =
+'Retorna o logaritmo de `x` na base dada.'
+math.log10 =
+'Retorna o logaritmo `x` na base 10.'
+math.max =
+'Retorna o argumento com o valor máximo de acordo com o operador `<`.'
+math.maxinteger =
+'Retorna o valor máximo para um inteiro.'
+math.min =
+'Retorna o argumento com o valor mínimo de acordo com o operador `<`.'
+math.mininteger =
+'Retorna o valor mínimo para um inteiro.'
+math.modf =
+'Retorna a parte inteira e a parte fracionária de `x`.'
+math.pi =
+'O valor de *π*.'
+math.pow =
+'Retorna `x ^ y`.'
+math.rad =
+'Converte o ângulo `x` de graus para radianos.'
+math.random =
+[[
* `math.random()`: Retorna um valor real (i.e., ponto flutuante) no intervalo [0,1).
* `math.random(n)`: Retorna um inteiro no intervalo [1, n].
* `math.random(m, n)`: Retorna um inteiro no intervalo [m, n].
]]
-math.randomseed['<5.3'] = 'Define `x` como valor semente (i.e., `seed`) para a função geradora de números pseudo-aleatória.'
-math.randomseed['>5.4'] = [[
+math.randomseed['<5.3'] =
+'Define `x` como valor semente (i.e., `seed`) para a função geradora de números pseudo-aleatória.'
+math.randomseed['>5.4'] =
+[[
* `math.randomseed(x, y)`: Concatena `x` e `y` em um espaço de 128-bits que é usado como valor semente (`seed`) para reinicializar o gerador de números pseudo-aleatório.
* `math.randomseed(x)`: Equivale a `math.randomseed(x, 0)` .
* `math.randomseed()`: Gera um valor semente (i.e., `seed`) com fraca probabilidade de aleatoriedade.
]]
-math.sin = 'Retorna o seno de `x` (requer valor em radianos).'
-math.sinh = 'Retorna o seno hiperbólico de `x` (requer valor em radianos).'
-math.sqrt = 'Retorna a raiz quadrada de `x`.'
-math.tan = 'Retorna a tangente de `x` (requer valor em radianos).'
-math.tanh = 'Retorna a tangente hiperbólica de `x` (requer valor em radianos).'
-math.tointeger = 'Se o valor `x` pode ser convertido para um inteiro, retorna esse inteiro.'
-math.type = 'Retorna `"integer"` se `x` é um inteiro, `"float"` se for um valor real (i.e., ponto flutuante), ou `nil` se `x` não é um número.'
-math.ult = 'Retorna `true` se e somente se `m` é menor `n` quando eles são comparados como inteiros sem sinal.'
+math.sin =
+'Retorna o seno de `x` (requer valor em radianos).'
+math.sinh =
+'Retorna o seno hiperbólico de `x` (requer valor em radianos).'
+math.sqrt =
+'Retorna a raiz quadrada de `x`.'
+math.tan =
+'Retorna a tangente de `x` (requer valor em radianos).'
+math.tanh =
+'Retorna a tangente hiperbólica de `x` (requer valor em radianos).'
+math.tointeger =
+'Se o valor `x` pode ser convertido para um inteiro, retorna esse inteiro.'
+math.type =
+'Retorna `"integer"` se `x` é um inteiro, `"float"` se for um valor real (i.e., ponto flutuante), ou `nil` se `x` não é um número.'
+math.ult =
+'Retorna `true` se e somente se `m` é menor `n` quando eles são comparados como inteiros sem sinal.'
-os = ''
-os.clock = 'Retorna uma aproximação do valor, em segundos, do tempo de CPU usado pelo programa.'
-os.date = 'Retorna uma string ou uma tabela contendo data e hora, formatada de acordo com a string `format` fornecida.'
-os.difftime = 'Retorna a diferença, em segundos, do tempo `t1` para o tempo` t2`.'
-os.execute = 'Passa `command` para ser executado por um `shell` do sistema operacional.'
-os.exit['<5.1'] = 'Chama a função `exit` do C para encerrar o programa.'
-os.exit['>5.2'] = 'Chama a função `exit` do ISO C para encerrar o programa.'
-os.getenv = 'Retorna o valor da variável de ambiente de processo `varname`.'
-os.remove = 'Remove o arquivo com o nome dado.'
-os.rename = 'Renomeia o arquivo ou diretório chamado `oldname` para `newname`.'
-os.setlocale = 'Define a localidade atual do programa.'
-os.time = 'Retorna a hora atual quando chamada sem argumentos, ou um valor representando a data e a hora local especificados pela tabela fornecida.'
-os.tmpname = 'Retorna uma string com um nome de arquivo que pode ser usado como arquivo temporário.'
-osdate.year = 'Quatro dígitos.'
-osdate.month = '1-12'
-osdate.day = '1-31'
-osdate.hour = '0-23'
-osdate.min = '0-59'
-osdate.sec = '0-61'
-osdate.wday = 'Dia da semana, 1–7, Domingo é 1'
-osdate.yday = 'Dia do ano, 1–366'
-osdate.isdst = 'Bandeira para indicar horário de verão (i.e., `Daylight Saving Time`), um valor booleano.'
+os =
+''
+os.clock =
+'Retorna uma aproximação do valor, em segundos, do tempo de CPU usado pelo programa.'
+os.date =
+'Retorna uma string ou uma tabela contendo data e hora, formatada de acordo com a string `format` fornecida.'
+os.difftime =
+'Retorna a diferença, em segundos, do tempo `t1` para o tempo` t2`.'
+os.execute =
+'Passa `command` para ser executado por um `shell` do sistema operacional.'
+os.exit['<5.1'] =
+'Chama a função `exit` do C para encerrar o programa.'
+os.exit['>5.2'] =
+'Chama a função `exit` do ISO C para encerrar o programa.'
+os.getenv =
+'Retorna o valor da variável de ambiente de processo `varname`.'
+os.remove =
+'Remove o arquivo com o nome dado.'
+os.rename =
+'Renomeia o arquivo ou diretório chamado `oldname` para `newname`.'
+os.setlocale =
+'Define a localidade atual do programa.'
+os.time =
+'Retorna a hora atual quando chamada sem argumentos, ou um valor representando a data e a hora local especificados pela tabela fornecida.'
+os.tmpname =
+'Retorna uma string com um nome de arquivo que pode ser usado como arquivo temporário.'
+osdate.year =
+'Quatro dígitos.'
+osdate.month =
+'1-12'
+osdate.day =
+'1-31'
+osdate.hour =
+'0-23'
+osdate.min =
+'0-59'
+osdate.sec =
+'0-61'
+osdate.wday =
+'Dia da semana, 1–7, Domingo é 1'
+osdate.yday =
+'Dia do ano, 1–366'
+osdate.isdst =
+'Bandeira para indicar horário de verão (i.e., `Daylight Saving Time`), um valor booleano.'
-package = ''
-require['<5.3'] = 'Carrega o módulo fornecido e retorna qualquer valor retornado pelo módulo (`true` quando `nil`).'
-require['>5.4'] = 'Carrega o módulo fornecido e retorna qualquer valor retornado pelo pesquisador (`true` quando `nil`). Além desse valor, também retorna como segundo resultado um carregador de dados retornados pelo pesquisador, o que indica como `require` encontrou o módulo. (Por exemplo, se o módulo vier de um arquivo, este carregador de dados é o caminho do arquivo.)'
-package.config = 'string descrevendo configurações a serem utilizadas durante a compilação de pacotes.'
-package.cpath = 'O caminho usado pelo `require` para procurar pelo carregador C.'
-package.loaded = 'Uma tabela usada pelo `require` para controlar quais módulos já estão carregados.'
-package.loaders = 'Uma tabela usada pelo `require` para controlar como carregar módulos.'
-package.loadlib = 'Dinamicamente vincula o programa no `host` com a biblioteca C `libname`.'
-package.path = 'O caminho usado pelo `require` para procurar por um carregador Lua.'
-package.preload = 'Uma tabela para armazenar carregadores de módulos específicos.'
-package.searchers = 'Uma tabela usada pelo `require` para controlar como buscar módulos.'
-package.searchpath = 'Procura por `name` em `path`.'
-package.seeall = 'Define uma `metatable` `module` com o campo `__index` referenciando o ambiente global, para que este módulo herde valores do ambiente global. Para ser usado como uma opção a função `module`.'
+package =
+''
+require['<5.3'] =
+'Carrega o módulo fornecido e retorna qualquer valor retornado pelo módulo (`true` quando `nil`).'
+require['>5.4'] =
+'Carrega o módulo fornecido e retorna qualquer valor retornado pelo pesquisador (`true` quando `nil`). Além desse valor, também retorna como segundo resultado um carregador de dados retornados pelo pesquisador, o que indica como `require` encontrou o módulo. (Por exemplo, se o módulo vier de um arquivo, este carregador de dados é o caminho do arquivo.)'
+package.config =
+'string descrevendo configurações a serem utilizadas durante a compilação de pacotes.'
+package.cpath =
+'O caminho usado pelo `require` para procurar pelo carregador C.'
+package.loaded =
+'Uma tabela usada pelo `require` para controlar quais módulos já estão carregados.'
+package.loaders =
+'Uma tabela usada pelo `require` para controlar como carregar módulos.'
+package.loadlib =
+'Dinamicamente vincula o programa no `host` com a biblioteca C `libname`.'
+package.path =
+'O caminho usado pelo `require` para procurar por um carregador Lua.'
+package.preload =
+'Uma tabela para armazenar carregadores de módulos específicos.'
+package.searchers =
+'Uma tabela usada pelo `require` para controlar como buscar módulos.'
+package.searchpath =
+'Procura por `name` em `path`.'
+package.seeall =
+'Define uma `metatable` `module` com o campo `__index` referenciando o ambiente global, para que este módulo herde valores do ambiente global. Para ser usado como uma opção a função `module`.'
-string = ''
-string.byte = 'Retorna os códigos numéricos internos dos caracteres `s[i], s[i+1], ..., s[j]`.'
-string.char = 'Retorna uma string com comprimento igual ao número de argumentos, no qual cada caractere possui o código numérico interno igual ao seu argumento correspondente.'
-string.dump = 'Retorna uma string contendo uma representação binária (i.e., *binary chunk*) da função dada.'
-string.find = 'Procura a primeira correspondencia de `pattern` (veja §6.4.1) na string.'
-string.format = 'Retorna uma versão formatada de seu número variável de argumentos após a descrição dada em seu primeiro argumento.'
-string.gmatch = [[
+string =
+''
+string.byte =
+'Retorna os códigos numéricos internos dos caracteres `s[i], s[i+1], ..., s[j]`.'
+string.char =
+'Retorna uma string com comprimento igual ao número de argumentos, no qual cada caractere possui o código numérico interno igual ao seu argumento correspondente.'
+string.dump =
+'Retorna uma string contendo uma representação binária (i.e., *binary chunk*) da função dada.'
+string.find =
+'Procura a primeira correspondencia de `pattern` (veja §6.4.1) na string.'
+string.format =
+'Retorna uma versão formatada de seu número variável de argumentos após a descrição dada em seu primeiro argumento.'
+string.gmatch =
+[[
Retorna um iterator que, a cada vez que é chamado, retorna as próximas capturas de `pattern` (veja §6.4.1) sobre a string *s*.
Por exemplo, o loop a seguir irá iterar em todas as palavras da string *s*, imprimindo cada palavra por linha:
```lua
- s = "hello world from Lua"
+ s =
+"hello world from Lua"
for w in string.gmatch(s, "%a+") do
print(w)
end
```
]]
-string.gsub = 'Retorna uma cópia da *s* em que todas ou, caso fornecido, as primeiras `n` ocorrências de `pattern` (veja §6.4.1) que tiverem sido substituídas por uma string de substituição especificada por `repl`.'
-string.len = 'Retorna o comprimento da string.'
-string.lower = 'Retorna uma cópia desta string com todas as letras maiúsculas alteradas para minúsculas.'
-string.match = 'Procura a primeira ocorrência do `pattern` (veja §6.4.1) na string.'
-string.pack = 'Retorna uma string binária contendo os valores `V1`, `v2`, etc. empacotados (isto é, serializado de forma binário) de acordo com o formato da string `fmt` fornecida (veja §6.4.2).'
-string.packsize = 'Retorna o tamanho de uma string resultante de `string.pack` com o formato da string `fmt` fornecida (veja §6.4.2).'
-string.rep['>5.2'] = 'Retorna uma string que é a concatenação de `n` cópias da string `s` separadas pela string `sep`.'
-string.rep['<5.1'] = 'Retorna uma string que é a concatenação de `n` cópias da string `s`.'
-string.reverse = 'Retorna uma string que representa a string `s` invertida.'
-string.sub = 'Retorna a substring da string `s` que começa no índice `i` e continua até o índice `j`.'
-string.unpack = 'Retorna os valores empacotados na string de acordo com o formato da string `fmt` fornecida (veja §6.4.2).'
-string.upper = 'Retorna uma cópia desta string com todas as letras minúsculas alteradas para maiúsculas.'
+string.gsub =
+'Retorna uma cópia da *s* em que todas ou, caso fornecido, as primeiras `n` ocorrências de `pattern` (veja §6.4.1) que tiverem sido substituídas por uma string de substituição especificada por `repl`.'
+string.len =
+'Retorna o comprimento da string.'
+string.lower =
+'Retorna uma cópia desta string com todas as letras maiúsculas alteradas para minúsculas.'
+string.match =
+'Procura a primeira ocorrência do `pattern` (veja §6.4.1) na string.'
+string.pack =
+'Retorna uma string binária contendo os valores `V1`, `v2`, etc. empacotados (isto é, serializado de forma binário) de acordo com o formato da string `fmt` fornecida (veja §6.4.2).'
+string.packsize =
+'Retorna o tamanho de uma string resultante de `string.pack` com o formato da string `fmt` fornecida (veja §6.4.2).'
+string.rep['>5.2'] =
+'Retorna uma string que é a concatenação de `n` cópias da string `s` separadas pela string `sep`.'
+string.rep['<5.1'] =
+'Retorna uma string que é a concatenação de `n` cópias da string `s`.'
+string.reverse =
+'Retorna uma string que representa a string `s` invertida.'
+string.sub =
+'Retorna a substring da string `s` que começa no índice `i` e continua até o índice `j`.'
+string.unpack =
+'Retorna os valores empacotados na string de acordo com o formato da string `fmt` fornecida (veja §6.4.2).'
+string.upper =
+'Retorna uma cópia desta string com todas as letras minúsculas alteradas para maiúsculas.'
-table = ''
-table.concat = 'Dada uma lista onde todos os elementos são strings ou números, retorna a string `list[i]..sep..list[i+1] ··· sep..list[j]`.'
-table.insert = 'Insere o elemento `value` na posição `pos` de `list`.'
-table.maxn = 'Retorna o maior índice numérico positivo da tabela fornecida ou zero se a tabela não tiver índices numéricos positivos.'
-table.move = [[
+table =
+''
+table.concat =
+'Dada uma lista onde todos os elementos são strings ou números, retorna a string `list[i]..sep..list[i+1] ··· sep..list[j]`.'
+table.insert =
+'Insere o elemento `value` na posição `pos` de `list`.'
+table.maxn =
+'Retorna o maior índice numérico positivo da tabela fornecida ou zero se a tabela não tiver índices numéricos positivos.'
+table.move =
+[[
Move os elementos da tabela `a1` para tabela `a2`.
```lua
-a2[t],··· = a1[f],···,a1[e]
+a2[t],··· =
+a1[f],···,a1[e]
return a2
```
]]
-table.pack = 'Retorna uma nova tabela com todos os argumentos armazenados em chaves `1`, `2`, etc. e com um campo `"n"` com o número total de argumentos.'
-table.remove = 'Remove de `list` o elemento na posição `pos`, retornando o valor do elemento removido.'
-table.sort = 'Ordena os elementos de `list` em uma determinada ordem, *in-place*, de `list[1]` para `list[#list]`.'
-table.unpack = [[
+table.pack =
+'Retorna uma nova tabela com todos os argumentos armazenados em chaves `1`, `2`, etc. e com um campo `"n"` com o número total de argumentos.'
+table.remove =
+'Remove de `list` o elemento na posição `pos`, retornando o valor do elemento removido.'
+table.sort =
+'Ordena os elementos de `list` em uma determinada ordem, *in-place*, de `list[1]` para `list[#list]`.'
+table.unpack =
+[[
Retorna os elementos da lista fornecida. Esta função é equivalente a
```lua
return list[i], list[i+1], ···, list[j]
@@ -413,10 +678,14 @@ Retorna os elementos da lista fornecida. Esta função é equivalente a
Por padrão, `i` é `1` e `j` é `#list`.
]]
-utf8 = ''
-utf8.char = 'Recebe zero ou mais inteiros, converte cada um à sua sequência de byte UTF-8 correspondente e retorna uma string com a concatenação de todas essas sequências.'
-utf8.charpattern = 'O padrão que corresponde exatamente uma sequência de byte UTF-8, supondo que seja uma sequência válida UTF-8.'
-utf8.codes = [[
+utf8 =
+''
+utf8.char =
+'Recebe zero ou mais inteiros, converte cada um à sua sequência de byte UTF-8 correspondente e retorna uma string com a concatenação de todas essas sequências.'
+utf8.charpattern =
+'O padrão que corresponde exatamente uma sequência de byte UTF-8, supondo que seja uma sequência válida UTF-8.'
+utf8.codes =
+[[
Retorna valores tal que a seguinte construção
```lua
for p, c in utf8.codes(s) do
@@ -425,7 +694,11 @@ end
```
itere em todos os caracteres UTF-8 na string s, com p sendo a posição (em bytes) e c o *codepoint* de cada caractere. Ele gera um erro se encontrado qualquer sequência de byte inválida.
]]
-utf8.codepoint = 'Retorna os *codepoints* (em inteiros) de todos os caracteres em `s` que iniciam entre as posições do byte `i` e `j` (ambos inclusos).'
-utf8.len = 'Retorna o número de caracteres UTF-8 na string `s` que começa entre as posições `i` e `j` (ambos inclusos).'
-utf8.offset = 'Returns the position (in bytes) where the encoding of the `n`-th character of `s` (counting from position `i`) starts.'
-utf8.offset = 'Retorna a posição (em bytes) onde a codificação do `n`-ésimo caractere de `s` inícia (contando a partir da posição `i`).'
+utf8.codepoint =
+'Retorna os *codepoints* (em inteiros) de todos os caracteres em `s` que iniciam entre as posições do byte `i` e `j` (ambos inclusos).'
+utf8.len =
+'Retorna o número de caracteres UTF-8 na string `s` que começa entre as posições `i` e `j` (ambos inclusos).'
+utf8.offset =
+'Returns the position (in bytes) where the encoding of the `n`-th character of `s` (counting from position `i`) starts.'
+utf8.offset =
+'Retorna a posição (em bytes) onde a codificação do `n`-ésimo caractere de `s` inícia (contando a partir da posição `i`).'
diff --git a/locale/pt-br/script.lua b/locale/pt-br/script.lua
index 255ad787..aa16c3d3 100644
--- a/locale/pt-br/script.lua
+++ b/locale/pt-br/script.lua
@@ -1,268 +1,505 @@
-DIAG_LINE_ONLY_SPACE = 'Linha com espaços apenas.'
-DIAG_LINE_POST_SPACE = 'Linha com espaço extra ao final.'
-DIAG_UNUSED_LOCAL = 'Escopo não utilizado `{}`.'
-DIAG_UNDEF_GLOBAL = 'Escopo global indefinido `{}`.'
-DIAG_UNDEF_FIELD = 'Campo indefinido `{}`.'
-DIAG_UNDEF_ENV_CHILD = 'Variável indefinida `{}` (overloaded `_ENV` ).'
-DIAG_UNDEF_FENV_CHILD = 'Variável indefinida `{}` (módulo interno).'
-DIAG_GLOBAL_IN_NIL_ENV = 'Valor global inválido (`_ENV` é `nil`).'
-DIAG_GLOBAL_IN_NIL_FENV = 'Valor global inválido (Ambiente do módulo é `nil`).'
-DIAG_UNUSED_LABEL = 'Identificador não utilizado `{}`.'
-DIAG_UNUSED_FUNCTION = 'Funções não utilizadas.'
-DIAG_UNUSED_VARARG = 'vararg não utilizado.'
-DIAG_REDEFINED_LOCAL = 'Valor local redefinido `{}`.'
-DIAG_DUPLICATE_INDEX = 'Índice duplicado `{}`.'
-DIAG_DUPLICATE_METHOD = 'Método duplicado `{}`.'
-DIAG_PREVIOUS_CALL = 'Será interpretado como `{}{}`. Pode ser necessário adicionar uma `,`.'
-DIAG_PREFIELD_CALL = 'Será interpretado como `{}{}`. Pode ser necessário adicionar uma `,` ou `;`.'
-DIAG_OVER_MAX_ARGS = 'A função aceita apenas os parâmetros {:d}, mas você passou {:d}.'
-DIAG_OVER_MAX_ARGS = 'Recebe apenas {} variáveis, mas você definiu {}.'
-DIAG_AMBIGUITY_1 = 'Calcule primeiro `{}`. Você pode precisar adicionar colchetes.'
-DIAG_LOWERCASE_GLOBAL = 'Variável global com inicial minúscula, você esqueceu o `local` ou digitou errado?'
-DIAG_EMPTY_BLOCK = 'Bloco vazio.'
-DIAG_DIAGNOSTICS = 'Diagnósticos Lua.'
-DIAG_SYNTAX_CHECK = 'Verificação de sintaxe Lua.'
-DIAG_NEED_VERSION = 'Suportado em {}, atual é {}.'
-DIAG_DEFINED_VERSION = 'Definido em {}, a corrente é {}.'
-DIAG_DEFINED_CUSTOM = 'Definido em {}.'
-DIAG_DUPLICATE_CLASS = 'Classe duplicada `{}`.'
-DIAG_UNDEFINED_CLASS = 'Classe indefinida `{}`.'
-DIAG_CYCLIC_EXTENDS = 'Herança cíclica.'
-DIAG_INEXISTENT_PARAM = 'Parâmetro inexistente.'
-DIAG_DUPLICATE_PARAM = 'Parâmetro duplicado.'
-DIAG_NEED_CLASS = 'Classe precisa ser definida primeiro.'
-DIAG_DUPLICATE_SET_FIELD= 'Campo duplicado `{}`.'
-DIAG_SET_CONST = 'Atribuição à variável constante.'
-DIAG_SET_FOR_STATE = 'Atribuição à variável to tipo for-state.'
-DIAG_CODE_AFTER_BREAK = 'Não é possível executar o código depois `break`.'
-DIAG_UNBALANCED_ASSIGNMENTS = 'O valor é atribuído como `nil` porque o número de valores não é suficiente. Em Lua, `x, y = 1` é equivalente a `x, y = 1, nil` .'
-DIAG_REQUIRE_LIKE = 'Você pode tratar `{}` como `require` por configuração.'
-DIAG_COSE_NON_OBJECT = 'Não é possível fechar um valor desse tipo. (A menos que se defina o meta método `__close`)'
-DIAG_COUNT_DOWN_LOOP = 'Você quer dizer `{}` ?'
-DIAG_IMPLICIT_ANY = 'Não pode inferir tipo.'
-DIAG_DEPRECATED = 'Descontinuada.'
-DIAG_DIFFERENT_REQUIRES = 'O mesmo arquivo é necessário com nomes diferentes.'
-DIAG_REDUNDANT_RETURN = 'Retorno redundante.'
+DIAG_LINE_ONLY_SPACE =
+'Linha com espaços apenas.'
+DIAG_LINE_POST_SPACE =
+'Linha com espaço extra ao final.'
+DIAG_UNUSED_LOCAL =
+'Escopo não utilizado `{}`.'
+DIAG_UNDEF_GLOBAL =
+'Escopo global indefinido `{}`.'
+DIAG_UNDEF_FIELD =
+'Campo indefinido `{}`.'
+DIAG_UNDEF_ENV_CHILD =
+'Variável indefinida `{}` (overloaded `_ENV` ).'
+DIAG_UNDEF_FENV_CHILD =
+'Variável indefinida `{}` (módulo interno).'
+DIAG_GLOBAL_IN_NIL_ENV =
+'Valor global inválido (`_ENV` é `nil`).'
+DIAG_GLOBAL_IN_NIL_FENV =
+'Valor global inválido (Ambiente do módulo é `nil`).'
+DIAG_UNUSED_LABEL =
+'Identificador não utilizado `{}`.'
+DIAG_UNUSED_FUNCTION =
+'Funções não utilizadas.'
+DIAG_UNUSED_VARARG =
+'vararg não utilizado.'
+DIAG_REDEFINED_LOCAL =
+'Valor local redefinido `{}`.'
+DIAG_DUPLICATE_INDEX =
+'Índice duplicado `{}`.'
+DIAG_DUPLICATE_METHOD =
+'Método duplicado `{}`.'
+DIAG_PREVIOUS_CALL =
+'Será interpretado como `{}{}`. Pode ser necessário adicionar uma `,`.'
+DIAG_PREFIELD_CALL =
+'Será interpretado como `{}{}`. Pode ser necessário adicionar uma `,` ou `;`.'
+DIAG_OVER_MAX_ARGS =
+'A função aceita apenas os parâmetros {:d}, mas você passou {:d}.'
+DIAG_OVER_MAX_ARGS =
+'Recebe apenas {} variáveis, mas você definiu {}.'
+DIAG_AMBIGUITY_1 =
+'Calcule primeiro `{}`. Você pode precisar adicionar colchetes.'
+DIAG_LOWERCASE_GLOBAL =
+'Variável global com inicial minúscula, você esqueceu o `local` ou digitou errado?'
+DIAG_EMPTY_BLOCK =
+'Bloco vazio.'
+DIAG_DIAGNOSTICS =
+'Diagnósticos Lua.'
+DIAG_SYNTAX_CHECK =
+'Verificação de sintaxe Lua.'
+DIAG_NEED_VERSION =
+'Suportado em {}, atual é {}.'
+DIAG_DEFINED_VERSION =
+'Definido em {}, a corrente é {}.'
+DIAG_DEFINED_CUSTOM =
+'Definido em {}.'
+DIAG_DUPLICATE_CLASS =
+'Classe duplicada `{}`.'
+DIAG_UNDEFINED_CLASS =
+'Classe indefinida `{}`.'
+DIAG_CYCLIC_EXTENDS =
+'Herança cíclica.'
+DIAG_INEXISTENT_PARAM =
+'Parâmetro inexistente.'
+DIAG_DUPLICATE_PARAM =
+'Parâmetro duplicado.'
+DIAG_NEED_CLASS =
+'Classe precisa ser definida primeiro.'
+DIAG_DUPLICATE_SET_FIELD=
+'Campo duplicado `{}`.'
+DIAG_SET_CONST =
+'Atribuição à variável constante.'
+DIAG_SET_FOR_STATE =
+'Atribuição à variável to tipo for-state.'
+DIAG_CODE_AFTER_BREAK =
+'Não é possível executar o código depois `break`.'
+DIAG_UNBALANCED_ASSIGNMENTS =
+'O valor é atribuído como `nil` porque o número de valores não é suficiente. Em Lua, `x, y = 1` é equivalente a `x, y = 1, nil` .'
+DIAG_REQUIRE_LIKE =
+'Você pode tratar `{}` como `require` por configuração.'
+DIAG_COSE_NON_OBJECT =
+'Não é possível fechar um valor desse tipo. (A menos que se defina o meta método `__close`)'
+DIAG_COUNT_DOWN_LOOP =
+'Você quer dizer `{}` ?'
+DIAG_IMPLICIT_ANY =
+'Não pode inferir tipo.'
+DIAG_DEPRECATED =
+'Descontinuada.'
+DIAG_DIFFERENT_REQUIRES =
+'O mesmo arquivo é necessário com nomes diferentes.'
+DIAG_REDUNDANT_RETURN =
+'Retorno redundante.'
-DIAG_CIRCLE_DOC_CLASS = 'Classes com herança cíclica.'
-DIAG_DOC_FIELD_NO_CLASS = 'O campo deve ser definido após a classe.'
-DIAG_DUPLICATE_DOC_CLASS = 'Classe definida duplicada `{}`.'
-DIAG_DUPLICATE_DOC_FIELD = 'Campos definidos duplicados `{}`.'
-DIAG_DUPLICATE_DOC_PARAM = 'Parâmetros duplicados `{}`.'
-DIAG_UNDEFINED_DOC_CLASS = 'Classe indefinida `{}`.'
-DIAG_UNDEFINED_DOC_NAME = 'Tipo ou alias indefinido `{}`.'
-DIAG_UNDEFINED_DOC_PARAM = 'Parâmetro indefinido `{}`.'
-DIAG_UNKNOWN_DIAG_CODE = 'Código de diagnóstico desconhecido `{}`.'
+DIAG_CIRCLE_DOC_CLASS =
+'Classes com herança cíclica.'
+DIAG_DOC_FIELD_NO_CLASS =
+'O campo deve ser definido após a classe.'
+DIAG_DUPLICATE_DOC_CLASS =
+'Classe definida duplicada `{}`.'
+DIAG_DUPLICATE_DOC_FIELD =
+'Campos definidos duplicados `{}`.'
+DIAG_DUPLICATE_DOC_PARAM =
+'Parâmetros duplicados `{}`.'
+DIAG_UNDEFINED_DOC_CLASS =
+'Classe indefinida `{}`.'
+DIAG_UNDEFINED_DOC_NAME =
+'Tipo ou alias indefinido `{}`.'
+DIAG_UNDEFINED_DOC_PARAM =
+'Parâmetro indefinido `{}`.'
+DIAG_UNKNOWN_DIAG_CODE =
+'Código de diagnóstico desconhecido `{}`.'
-MWS_NOT_SUPPORT = '{} não é suportado múltiplos espaços de trabalho por enquanto, posso precisar reiniciar para estabelecer um novo espaço de trabalho ...'
-MWS_RESTART = 'Reiniciar'
-MWS_NOT_COMPLETE = 'O espaço de trabalho ainda não está completo. Você pode tentar novamente mais tarde ...'
-MWS_COMPLETE = 'O espaço de trabalho está completo agora. Você pode tentar novamente ...'
-MWS_MAX_PRELOAD = 'Arquivos pré-carregados atingiram o limite máximo ({}), você precisa abrir manualmente os arquivos que precisam ser carregados.'
-MWS_UCONFIG_FAILED = 'Armazenamento da configuração do usuário falhou.'
-MWS_UCONFIG_UPDATED = 'Configuração do usuário atualizada.'
-MWS_WCONFIG_UPDATED = 'Configuração do espaço de trabalho atualizado.'
+MWS_NOT_SUPPORT =
+'{} não é suportado múltiplos espaços de trabalho por enquanto, posso precisar reiniciar para estabelecer um novo espaço de trabalho ...'
+MWS_RESTART =
+'Reiniciar'
+MWS_NOT_COMPLETE =
+'O espaço de trabalho ainda não está completo. Você pode tentar novamente mais tarde ...'
+MWS_COMPLETE =
+'O espaço de trabalho está completo agora. Você pode tentar novamente ...'
+MWS_MAX_PRELOAD =
+'Arquivos pré-carregados atingiram o limite máximo ({}), você precisa abrir manualmente os arquivos que precisam ser carregados.'
+MWS_UCONFIG_FAILED =
+'Armazenamento da configuração do usuário falhou.'
+MWS_UCONFIG_UPDATED =
+'Configuração do usuário atualizada.'
+MWS_WCONFIG_UPDATED =
+'Configuração do espaço de trabalho atualizado.'
-WORKSPACE_SKIP_LARGE_FILE = 'Arquivo muito grande: {} ignorada. O limite de tamanho atualmente definido é: {} KB, e o tamanho do arquivo é: {} KB.'
-WORKSPACE_LOADING = 'Carregando espaço de trabalho.'
-WORKSPACE_DIAGNOSTIC = 'Diagnóstico de espaço de trabalho.'
-WORKSPACE_SKIP_HUGE_FILE = 'Por motivos de desempenho, a análise deste arquivo foi interrompida: {}'
+WORKSPACE_SKIP_LARGE_FILE =
+'Arquivo muito grande: {} ignorada. O limite de tamanho atualmente definido é: {} KB, e o tamanho do arquivo é: {} KB.'
+WORKSPACE_LOADING =
+'Carregando espaço de trabalho.'
+WORKSPACE_DIAGNOSTIC =
+'Diagnóstico de espaço de trabalho.'
+WORKSPACE_SKIP_HUGE_FILE =
+'Por motivos de desempenho, a análise deste arquivo foi interrompida: {}'
-PARSER_CRASH = 'Parser quebrou! Últimas palavras: {}'
-PARSER_UNKNOWN = 'Erro de sintaxe desconhecido ...'
-PARSER_MISS_NAME = '<name> esperado.'
-PARSER_UNKNOWN_SYMBOL = 'Símbolo inesperado `{symbol}`.'
-PARSER_MISS_SYMBOL = 'Símbolo não encontrado `{symbol}`.'
-PARSER_MISS_ESC_X = 'Deve ser 2 dígitos hexadecimais.'
-PARSER_UTF8_SMALL = 'Pelo menos 1 dígito hexadecimal.'
-PARSER_UTF8_MAX = 'Deve estar entre {min} e {max}.'
-PARSER_ERR_ESC = 'Sequência de saída inválida.'
-PARSER_MUST_X16 = 'Deve ser dígitos hexadecimais.'
-PARSER_MISS_EXPONENT = 'Dígitos perdidos para o expoente.'
-PARSER_MISS_EXP = '<exp> esperada.'
-PARSER_MISS_FIELD = '<field> esperado.'
-PARSER_MISS_METHOD = '<method> esperado.'
-PARSER_ARGS_AFTER_DOTS = '`...` deve ser o último argumento.'
-PARSER_KEYWORD = '<keyword> não pode ser usado como nome.'
-PARSER_EXP_IN_ACTION = 'Inesperada <exp>.'
-PARSER_BREAK_OUTSIDE = '<break> não está dentro de um loop.'
-PARSER_MALFORMED_NUMBER = 'Número malformado.'
-PARSER_ACTION_AFTER_RETURN = '<eof> esperado após `return`.'
-PARSER_ACTION_AFTER_BREAK = '<eof> esperado após `break`.'
-PARSER_NO_VISIBLE_LABEL = 'Nenhum identificador visível `{label}` .'
-PARSER_REDEFINE_LABEL = 'Identificador `{label}` já foi definido.'
-PARSER_UNSUPPORT_SYMBOL = '{version} não suporta esta gramática.'
-PARSER_UNEXPECT_DOTS = 'Não pode usar `...` fora de uma função vararg.'
-PARSER_UNEXPECT_SYMBOL = 'Símbolo inesperado `{symbol}` .'
-PARSER_UNKNOWN_TAG = 'Atributo desconhecido.'
-PARSER_MULTI_TAG = 'Não suporta múltiplos atributos.'
-PARSER_UNEXPECT_LFUNC_NAME = 'A função local só pode usar identificadores como nome.'
-PARSER_UNEXPECT_EFUNC_NAME = 'Função como expressão não pode ser nomeada.'
-PARSER_ERR_LCOMMENT_END = 'Anotações em múltiplas linhas devem ser fechadas por `{symbol}` .'
-PARSER_ERR_C_LONG_COMMENT = 'Lua deve usar `--[[ ]]` para anotações em múltiplas linhas.'
-PARSER_ERR_LSTRING_END = 'String longa deve ser fechada por `{symbol}` .'
-PARSER_ERR_ASSIGN_AS_EQ = 'Deveria usar `=` para atribuição.'
-PARSER_ERR_EQ_AS_ASSIGN = 'Deveria usar `==` para comparação de igualdade.'
-PARSER_ERR_UEQ = 'Deveria usar `~=` para comparação de desigualdade.'
-PARSER_ERR_THEN_AS_DO = 'Deveria usar `then` .'
-PARSER_ERR_DO_AS_THEN = 'Deveria usar `do` .'
-PARSER_MISS_END = 'Falta o `end` correspondente.'
-PARSER_ERR_COMMENT_PREFIX = 'Lua usa `--` para anotações/comentários.'
-PARSER_MISS_SEP_IN_TABLE = 'Falta o símbolo `,` ou `;` .'
-PARSER_SET_CONST = 'Atribuição à variável constante.'
-PARSER_UNICODE_NAME = 'Contém caracteres Unicode.'
-PARSER_ERR_NONSTANDARD_SYMBOL = 'Deveria usar `{symbol}`.'
-PARSER_MISS_SPACE_BETWEEN = 'Devem ser deixados espaços entre símbolos.'
-PARSER_INDEX_IN_FUNC_NAME = 'A forma `[name]` não pode ser usada em nome de uma função nomeada.'
-PARSER_UNKNOWN_ATTRIBUTE = 'Atributo local deve ser `const` ou `close`'
+PARSER_CRASH =
+'Parser quebrou! Últimas palavras: {}'
+PARSER_UNKNOWN =
+'Erro de sintaxe desconhecido ...'
+PARSER_MISS_NAME =
+'<name> esperado.'
+PARSER_UNKNOWN_SYMBOL =
+'Símbolo inesperado `{symbol}`.'
+PARSER_MISS_SYMBOL =
+'Símbolo não encontrado `{symbol}`.'
+PARSER_MISS_ESC_X =
+'Deve ser 2 dígitos hexadecimais.'
+PARSER_UTF8_SMALL =
+'Pelo menos 1 dígito hexadecimal.'
+PARSER_UTF8_MAX =
+'Deve estar entre {min} e {max}.'
+PARSER_ERR_ESC =
+'Sequência de saída inválida.'
+PARSER_MUST_X16 =
+'Deve ser dígitos hexadecimais.'
+PARSER_MISS_EXPONENT =
+'Dígitos perdidos para o expoente.'
+PARSER_MISS_EXP =
+'<exp> esperada.'
+PARSER_MISS_FIELD =
+'<field> esperado.'
+PARSER_MISS_METHOD =
+'<method> esperado.'
+PARSER_ARGS_AFTER_DOTS =
+'`...` deve ser o último argumento.'
+PARSER_KEYWORD =
+'<keyword> não pode ser usado como nome.'
+PARSER_EXP_IN_ACTION =
+'Inesperada <exp>.'
+PARSER_BREAK_OUTSIDE =
+'<break> não está dentro de um loop.'
+PARSER_MALFORMED_NUMBER =
+'Número malformado.'
+PARSER_ACTION_AFTER_RETURN =
+'<eof> esperado após `return`.'
+PARSER_ACTION_AFTER_BREAK =
+'<eof> esperado após `break`.'
+PARSER_NO_VISIBLE_LABEL =
+'Nenhum identificador visível `{label}` .'
+PARSER_REDEFINE_LABEL =
+'Identificador `{label}` já foi definido.'
+PARSER_UNSUPPORT_SYMBOL =
+'{version} não suporta esta gramática.'
+PARSER_UNEXPECT_DOTS =
+'Não pode usar `...` fora de uma função vararg.'
+PARSER_UNEXPECT_SYMBOL =
+'Símbolo inesperado `{symbol}` .'
+PARSER_UNKNOWN_TAG =
+'Atributo desconhecido.'
+PARSER_MULTI_TAG =
+'Não suporta múltiplos atributos.'
+PARSER_UNEXPECT_LFUNC_NAME =
+'A função local só pode usar identificadores como nome.'
+PARSER_UNEXPECT_EFUNC_NAME =
+'Função como expressão não pode ser nomeada.'
+PARSER_ERR_LCOMMENT_END =
+'Anotações em múltiplas linhas devem ser fechadas por `{symbol}` .'
+PARSER_ERR_C_LONG_COMMENT =
+'Lua deve usar `--[[ ]]` para anotações em múltiplas linhas.'
+PARSER_ERR_LSTRING_END =
+'String longa deve ser fechada por `{symbol}` .'
+PARSER_ERR_ASSIGN_AS_EQ =
+'Deveria usar `=` para atribuição.'
+PARSER_ERR_EQ_AS_ASSIGN =
+'Deveria usar `==` para comparação de igualdade.'
+PARSER_ERR_UEQ =
+'Deveria usar `~=` para comparação de desigualdade.'
+PARSER_ERR_THEN_AS_DO =
+'Deveria usar `then` .'
+PARSER_ERR_DO_AS_THEN =
+'Deveria usar `do` .'
+PARSER_MISS_END =
+'Falta o `end` correspondente.'
+PARSER_ERR_COMMENT_PREFIX =
+'Lua usa `--` para anotações/comentários.'
+PARSER_MISS_SEP_IN_TABLE =
+'Falta o símbolo `,` ou `;` .'
+PARSER_SET_CONST =
+'Atribuição à variável constante.'
+PARSER_UNICODE_NAME =
+'Contém caracteres Unicode.'
+PARSER_ERR_NONSTANDARD_SYMBOL =
+'Deveria usar `{symbol}`.'
+PARSER_MISS_SPACE_BETWEEN =
+'Devem ser deixados espaços entre símbolos.'
+PARSER_INDEX_IN_FUNC_NAME =
+'A forma `[name]` não pode ser usada em nome de uma função nomeada.'
+PARSER_UNKNOWN_ATTRIBUTE =
+'Atributo local deve ser `const` ou `close`'
-PARSER_LUADOC_MISS_CLASS_NAME = 'Esperado <class name>.'
-PARSER_LUADOC_MISS_EXTENDS_SYMBOL = 'Esperado `:`.'
-PARSER_LUADOC_MISS_CLASS_EXTENDS_NAME = 'Esperado <class extends name>.'
-PARSER_LUADOC_MISS_SYMBOL = 'Esperado `{symbol}`.'
-PARSER_LUADOC_MISS_ARG_NAME = 'Esperado <arg name>.'
-PARSER_LUADOC_MISS_TYPE_NAME = 'Esperado <type name>.'
-PARSER_LUADOC_MISS_ALIAS_NAME = 'Esperado <alias name>.'
-PARSER_LUADOC_MISS_ALIAS_EXTENDS = 'Esperado <alias extends>.'
-PARSER_LUADOC_MISS_PARAM_NAME = 'Esperado <param name>.'
-PARSER_LUADOC_MISS_PARAM_EXTENDS = 'Esperado <param extends>.'
-PARSER_LUADOC_MISS_FIELD_NAME = 'Esperado <field name>.'
-PARSER_LUADOC_MISS_FIELD_EXTENDS = 'Esperado <field extends>.'
-PARSER_LUADOC_MISS_GENERIC_NAME = 'Esperado <generic name>.'
-PARSER_LUADOC_MISS_GENERIC_EXTENDS_NAME = 'Esperado <generic extends name>.'
-PARSER_LUADOC_MISS_VARARG_TYPE = 'Esperado <vararg type>.'
-PARSER_LUADOC_MISS_FUN_AFTER_OVERLOAD = 'Esperado `fun`.'
-PARSER_LUADOC_MISS_CATE_NAME = 'Esperado <doc name>.'
-PARSER_LUADOC_MISS_DIAG_MODE = 'Esperado <diagnostic mode>.'
-PARSER_LUADOC_ERROR_DIAG_MODE = '<diagnostic mode> incorreto.'
+PARSER_LUADOC_MISS_CLASS_NAME =
+'Esperado <class name>.'
+PARSER_LUADOC_MISS_EXTENDS_SYMBOL =
+'Esperado `:`.'
+PARSER_LUADOC_MISS_CLASS_EXTENDS_NAME =
+'Esperado <class extends name>.'
+PARSER_LUADOC_MISS_SYMBOL =
+'Esperado `{symbol}`.'
+PARSER_LUADOC_MISS_ARG_NAME =
+'Esperado <arg name>.'
+PARSER_LUADOC_MISS_TYPE_NAME =
+'Esperado <type name>.'
+PARSER_LUADOC_MISS_ALIAS_NAME =
+'Esperado <alias name>.'
+PARSER_LUADOC_MISS_ALIAS_EXTENDS =
+'Esperado <alias extends>.'
+PARSER_LUADOC_MISS_PARAM_NAME =
+'Esperado <param name>.'
+PARSER_LUADOC_MISS_PARAM_EXTENDS =
+'Esperado <param extends>.'
+PARSER_LUADOC_MISS_FIELD_NAME =
+'Esperado <field name>.'
+PARSER_LUADOC_MISS_FIELD_EXTENDS =
+'Esperado <field extends>.'
+PARSER_LUADOC_MISS_GENERIC_NAME =
+'Esperado <generic name>.'
+PARSER_LUADOC_MISS_GENERIC_EXTENDS_NAME =
+'Esperado <generic extends name>.'
+PARSER_LUADOC_MISS_VARARG_TYPE =
+'Esperado <vararg type>.'
+PARSER_LUADOC_MISS_FUN_AFTER_OVERLOAD =
+'Esperado `fun`.'
+PARSER_LUADOC_MISS_CATE_NAME =
+'Esperado <doc name>.'
+PARSER_LUADOC_MISS_DIAG_MODE =
+'Esperado <diagnostic mode>.'
+PARSER_LUADOC_ERROR_DIAG_MODE =
+'<diagnostic mode> incorreto.'
-SYMBOL_ANONYMOUS = '<Anonymous>'
+SYMBOL_ANONYMOUS =
+'<Anonymous>'
-HOVER_VIEW_DOCUMENTS = 'Visualizar documentos'
+HOVER_VIEW_DOCUMENTS =
+'Visualizar documentos'
-HOVER_DOCUMENT_LUA51 = 'http://www.lua.org/manual/5.1/manual.html#{}'
-HOVER_DOCUMENT_LUA52 = 'http://www.lua.org/manual/5.2/manual.html#{}'
-HOVER_DOCUMENT_LUA53 = 'http://www.lua.org/manual/5.3/manual.html#{}'
-HOVER_DOCUMENT_LUA54 = 'http://www.lua.org/manual/5.4/manual.html#{}'
-HOVER_DOCUMENT_LUAJIT = 'http://www.lua.org/manual/5.1/manual.html#{}'
+HOVER_DOCUMENT_LUA51 =
+'http://www.lua.org/manual/5.1/manual.html#{}'
+HOVER_DOCUMENT_LUA52 =
+'http://www.lua.org/manual/5.2/manual.html#{}'
+HOVER_DOCUMENT_LUA53 =
+'http://www.lua.org/manual/5.3/manual.html#{}'
+HOVER_DOCUMENT_LUA54 =
+'http://www.lua.org/manual/5.4/manual.html#{}'
+HOVER_DOCUMENT_LUAJIT =
+'http://www.lua.org/manual/5.1/manual.html#{}'
-HOVER_NATIVE_DOCUMENT_LUA51 = 'command:extension.lua.doc?["en-us/51/manual.html/{}"]'
-HOVER_NATIVE_DOCUMENT_LUA52 = 'command:extension.lua.doc?["en-us/52/manual.html/{}"]'
-HOVER_NATIVE_DOCUMENT_LUA53 = 'command:extension.lua.doc?["en-us/53/manual.html/{}"]'
-HOVER_NATIVE_DOCUMENT_LUA54 = 'command:extension.lua.doc?["en-us/54/manual.html/{}"]'
-HOVER_NATIVE_DOCUMENT_LUAJIT = 'command:extension.lua.doc?["en-us/51/manual.html/{}"]'
+HOVER_NATIVE_DOCUMENT_LUA51 =
+'command:extension.lua.doc?["en-us/51/manual.html/{}"]'
+HOVER_NATIVE_DOCUMENT_LUA52 =
+'command:extension.lua.doc?["en-us/52/manual.html/{}"]'
+HOVER_NATIVE_DOCUMENT_LUA53 =
+'command:extension.lua.doc?["en-us/53/manual.html/{}"]'
+HOVER_NATIVE_DOCUMENT_LUA54 =
+'command:extension.lua.doc?["en-us/54/manual.html/{}"]'
+HOVER_NATIVE_DOCUMENT_LUAJIT =
+'command:extension.lua.doc?["en-us/51/manual.html/{}"]'
-HOVER_MULTI_PROTOTYPE = '({} protótipos)'
-HOVER_STRING_BYTES = '{} bytes'
-HOVER_STRING_CHARACTERS = '{} bytes, {} caracteres'
-HOVER_MULTI_DEF_PROTO = '({} definições., {} protótipos)'
-HOVER_MULTI_PROTO_NOT_FUNC = '({} definição não funcional)'
+HOVER_MULTI_PROTOTYPE =
+'({} protótipos)'
+HOVER_STRING_BYTES =
+'{} bytes'
+HOVER_STRING_CHARACTERS =
+'{} bytes, {} caracteres'
+HOVER_MULTI_DEF_PROTO =
+'({} definições., {} protótipos)'
+HOVER_MULTI_PROTO_NOT_FUNC =
+'({} definição não funcional)'
-HOVER_USE_LUA_PATH = '(Caminho de busca: `{}`)'
-HOVER_EXTENDS = 'Expande para {}'
-HOVER_TABLE_TIME_UP = 'Inferência de tipo parcial foi desativada por motivos de desempenho.'
-HOVER_WS_LOADING = 'Carregando espaço de trabalho: {} / {}'
+HOVER_USE_LUA_PATH =
+'(Caminho de busca: `{}`)'
+HOVER_EXTENDS =
+'Expande para {}'
+HOVER_TABLE_TIME_UP =
+'Inferência de tipo parcial foi desativada por motivos de desempenho.'
+HOVER_WS_LOADING =
+'Carregando espaço de trabalho: {} / {}'
-ACTION_DISABLE_DIAG = 'Desativar diagnósticos no espaço de trabalho ({}).'
-ACTION_MARK_GLOBAL = 'Marque `{}` como definição global.'
-ACTION_REMOVE_SPACE = 'Limpe todos os espaços desnecessários.'
-ACTION_ADD_SEMICOLON = 'Adicione `;` .'
-ACTION_ADD_BRACKETS = 'Adicione colchetes.'
-ACTION_RUNTIME_VERSION = 'Altere a versão de tempo de execução para {}.'
-ACTION_OPEN_LIBRARY = 'Carregue variáveis globais de {}.'
-ACTION_ADD_DO_END = 'Adicione `do ... end`.'
-ACTION_FIX_LCOMMENT_END = 'Modifique para o símbolo de fechamento de anotação/comentário de múltiplas linhas correto.'
-ACTION_ADD_LCOMMENT_END = 'Feche as anotações/comentário de múltiplas linhas.'
-ACTION_FIX_C_LONG_COMMENT = 'Modifique para o formato de anotações/comentários em múltiplas linhas.'
-ACTION_FIX_LSTRING_END = 'Modifique para o símbolo de fechamento de string correta.'
-ACTION_ADD_LSTRING_END = 'Feche a string longa.'
-ACTION_FIX_ASSIGN_AS_EQ = 'Modifique para `=` .'
-ACTION_FIX_EQ_AS_ASSIGN = 'Modifique para `==` .'
-ACTION_FIX_UEQ = 'Modifique para `~=` .'
-ACTION_FIX_THEN_AS_DO = 'Modifique para `then` .'
-ACTION_FIX_DO_AS_THEN = 'Modifique para `do` .'
-ACTION_ADD_END = 'Adicione `end` (Adiciona marcação de fim com base na identação).'
-ACTION_FIX_COMMENT_PREFIX = 'Modifique para `--` .'
-ACTION_FIX_NONSTANDARD_SYMBOL = 'Modifique para `{symbol}` .'
-ACTION_RUNTIME_UNICODE_NAME = 'Permite caracteres Unicode.'
-ACTION_SWAP_PARAMS = 'Mude para o parâmetro {index} de `{node}`.'
-ACTION_FIX_INSERT_SPACE = 'Insira espaço.'
-ACTION_JSON_TO_LUA = 'Converte de JSON para Lua.'
-ACTION_DISABLE_DIAG_LINE= 'Desativa diagnósticos nesta linha ({}).'
-ACTION_DISABLE_DIAG_FILE= 'Desativa diagnósticos nesta linha ({}).'
+ACTION_DISABLE_DIAG =
+'Desativar diagnósticos no espaço de trabalho ({}).'
+ACTION_MARK_GLOBAL =
+'Marque `{}` como definição global.'
+ACTION_REMOVE_SPACE =
+'Limpe todos os espaços desnecessários.'
+ACTION_ADD_SEMICOLON =
+'Adicione `;` .'
+ACTION_ADD_BRACKETS =
+'Adicione colchetes.'
+ACTION_RUNTIME_VERSION =
+'Altere a versão de tempo de execução para {}.'
+ACTION_OPEN_LIBRARY =
+'Carregue variáveis globais de {}.'
+ACTION_ADD_DO_END =
+'Adicione `do ... end`.'
+ACTION_FIX_LCOMMENT_END =
+'Modifique para o símbolo de fechamento de anotação/comentário de múltiplas linhas correto.'
+ACTION_ADD_LCOMMENT_END =
+'Feche as anotações/comentário de múltiplas linhas.'
+ACTION_FIX_C_LONG_COMMENT =
+'Modifique para o formato de anotações/comentários em múltiplas linhas.'
+ACTION_FIX_LSTRING_END =
+'Modifique para o símbolo de fechamento de string correta.'
+ACTION_ADD_LSTRING_END =
+'Feche a string longa.'
+ACTION_FIX_ASSIGN_AS_EQ =
+'Modifique para `=` .'
+ACTION_FIX_EQ_AS_ASSIGN =
+'Modifique para `==` .'
+ACTION_FIX_UEQ =
+'Modifique para `~=` .'
+ACTION_FIX_THEN_AS_DO =
+'Modifique para `then` .'
+ACTION_FIX_DO_AS_THEN =
+'Modifique para `do` .'
+ACTION_ADD_END =
+'Adicione `end` (Adiciona marcação de fim com base na identação).'
+ACTION_FIX_COMMENT_PREFIX =
+'Modifique para `--` .'
+ACTION_FIX_NONSTANDARD_SYMBOL =
+'Modifique para `{symbol}` .'
+ACTION_RUNTIME_UNICODE_NAME =
+'Permite caracteres Unicode.'
+ACTION_SWAP_PARAMS =
+'Mude para o parâmetro {index} de `{node}`.'
+ACTION_FIX_INSERT_SPACE =
+'Insira espaço.'
+ACTION_JSON_TO_LUA =
+'Converte de JSON para Lua.'
+ACTION_DISABLE_DIAG_LINE=
+'Desativa diagnósticos nesta linha ({}).'
+ACTION_DISABLE_DIAG_FILE=
+'Desativa diagnósticos nesta linha ({}).'
-COMMAND_DISABLE_DIAG = 'Desativar diagnósticos.'
-COMMAND_MARK_GLOBAL = 'Marca como variável global.'
-COMMAND_REMOVE_SPACE = 'Limpa todos os espaços desnecessários.'
-COMMAND_ADD_BRACKETS = 'Adiciona colchetes.'
-COMMAND_RUNTIME_VERSION = 'Altera a versão de tempo de execução.'
-COMMAND_OPEN_LIBRARY = 'Carrega variáveis globais de bibliotecas de terceiros.'
-COMMAND_UNICODE_NAME = 'Permite caracteres Unicode.'
-COMMAND_JSON_TO_LUA = 'Converte de JSON para Lua.'
-COMMAND_JSON_TO_LUA_FAILED = 'Converção de JSON para Lua falhou: {}.'
+COMMAND_DISABLE_DIAG =
+'Desativar diagnósticos.'
+COMMAND_MARK_GLOBAL =
+'Marca como variável global.'
+COMMAND_REMOVE_SPACE =
+'Limpa todos os espaços desnecessários.'
+COMMAND_ADD_BRACKETS =
+'Adiciona colchetes.'
+COMMAND_RUNTIME_VERSION =
+'Altera a versão de tempo de execução.'
+COMMAND_OPEN_LIBRARY =
+'Carrega variáveis globais de bibliotecas de terceiros.'
+COMMAND_UNICODE_NAME =
+'Permite caracteres Unicode.'
+COMMAND_JSON_TO_LUA =
+'Converte de JSON para Lua.'
+COMMAND_JSON_TO_LUA_FAILED =
+'Converção de JSON para Lua falhou: {}.'
-COMPLETION_IMPORT_FROM = 'Importa de {}.'
-COMPLETION_DISABLE_AUTO_REQUIRE = 'Desativa auto require.'
-COMPLETION_ASK_AUTO_REQUIRE = 'Adicione o código na parte superior do arquivo como auto require?'
+COMPLETION_IMPORT_FROM =
+'Importa de {}.'
+COMPLETION_DISABLE_AUTO_REQUIRE =
+'Desativa auto require.'
+COMPLETION_ASK_AUTO_REQUIRE =
+'Adicione o código na parte superior do arquivo como auto require?'
-DEBUG_MEMORY_LEAK = "{} Sinto muito pelo sério vazamento de memória. O serviço de idioma será reiniciado em breve."
-DEBUG_RESTART_NOW = 'Reinicie agora'
+DEBUG_MEMORY_LEAK =
+"{} Sinto muito pelo sério vazamento de memória. O serviço de idioma será reiniciado em breve."
+DEBUG_RESTART_NOW =
+'Reinicie agora'
-WINDOW_COMPILING = 'Compilando'
-WINDOW_DIAGNOSING = 'Realizando diagnóstico'
-WINDOW_INITIALIZING = 'Inicializando...'
-WINDOW_PROCESSING_HOVER = 'Processando hover...'
-WINDOW_PROCESSING_DEFINITION = 'Processando definições...'
-WINDOW_PROCESSING_REFERENCE = 'Processando referências...'
-WINDOW_PROCESSING_RENAME = 'Processando renomeações...'
-WINDOW_PROCESSING_COMPLETION = 'Processando finalizações...'
-WINDOW_PROCESSING_SIGNATURE = 'Processando ajuda de assinatura...'
-WINDOW_PROCESSING_SYMBOL = 'Processando símbolos do arquivo...'
-WINDOW_PROCESSING_WS_SYMBOL = 'Processando símbolos do espaço de trabalho...'
-WINDOW_PROCESSING_SEMANTIC_FULL = 'Processando tokens semânticas completos...'
-WINDOW_PROCESSING_SEMANTIC_RANGE = 'Processando tokens semânticas incrementais...'
-WINDOW_PROCESSING_TYPE_HINT = 'Processando dicas de lina...'
-WINDOW_INCREASE_UPPER_LIMIT = 'Aumente o limite superior'
-WINDOW_CLOSE = 'Fechar'
-WINDOW_SETTING_WS_DIAGNOSTIC = 'Você pode atrasar ou desativar os diagnósticos do espaço de trabalho nas configurações'
-WINDOW_DONT_SHOW_AGAIN = 'Não mostre novamente'
-WINDOW_DELAY_WS_DIAGNOSTIC = 'Diagnóstico de tempo ocioso (atraso de {} segundos)'
-WINDOW_DISABLE_DIAGNOSTIC = 'Desativa diagnósticos do espaço de trabalho'
-WINDOW_LUA_STATUS_WORKSPACE = 'Área de trabalho : {}'
-WINDOW_LUA_STATUS_CACHED_FILES = 'Arquivos em cache: {ast}/{max}'
-WINDOW_LUA_STATUS_MEMORY_COUNT = 'Uso de memória : {mem:.f}M'
-WINDOW_APPLY_SETTING = 'Aplicar configuração'
-WINDOW_CHECK_SEMANTIC = 'Se você estiver usando o tema de cores do market, talvez seja necessário modificar `editor.semanticHighlighting.enabled` para `true` para fazer com tokens semânticas sejam habilitados.'
-WINDOW_TELEMETRY_HINT = 'Por favor, permita o envio de dados de uso e relatórios de erro anônimos para nos ajudar a melhorar ainda mais essa extensão. Leia nossa política de privacidade [aqui](https://github.com/sumneko/lua-language-server/wiki/Privacy-Policy) .'
-WINDOW_TELEMETRY_ENABLE = 'Permitir'
-WINDOW_TELEMETRY_DISABLE = 'Desabilitar'
-WINDOW_CLIENT_NOT_SUPPORT_CONFIG = 'Seu cliente não suporta configurações de modificação do lado do servidor, modifique manualmente as seguintes configurações:'
-WINDOW_LCONFIG_NOT_SUPPORT_CONFIG= 'A modificação automática de configurações locais não é suportada atualmente, modifique manualmente as seguintes configurações:'
-WINDOW_MANUAL_CONFIG_ADD = '`{key}`: adiciona o elemento `{value:q}` ;'
-WINDOW_MANUAL_CONFIG_SET = '`{key}`: defini como `{value:q}` ;'
-WINDOW_MANUAL_CONFIG_PROP = '`{key}`: define a propriedade `{prop}` para `{value:q}`;'
-WINDOW_APPLY_WHIT_SETTING = 'Aplicar e modificar configurações'
-WINDOW_APPLY_WHITOUT_SETTING = 'Aplicar mas não modificar configurações'
-WINDOW_ASK_APPLY_LIBRARY = 'Você precisa configurar seu ambiente de trabalho como `{}`?'
+WINDOW_COMPILING =
+'Compilando'
+WINDOW_DIAGNOSING =
+'Realizando diagnóstico'
+WINDOW_INITIALIZING =
+'Inicializando...'
+WINDOW_PROCESSING_HOVER =
+'Processando hover...'
+WINDOW_PROCESSING_DEFINITION =
+'Processando definições...'
+WINDOW_PROCESSING_REFERENCE =
+'Processando referências...'
+WINDOW_PROCESSING_RENAME =
+'Processando renomeações...'
+WINDOW_PROCESSING_COMPLETION =
+'Processando finalizações...'
+WINDOW_PROCESSING_SIGNATURE =
+'Processando ajuda de assinatura...'
+WINDOW_PROCESSING_SYMBOL =
+'Processando símbolos do arquivo...'
+WINDOW_PROCESSING_WS_SYMBOL =
+'Processando símbolos do espaço de trabalho...'
+WINDOW_PROCESSING_SEMANTIC_FULL =
+'Processando tokens semânticas completos...'
+WINDOW_PROCESSING_SEMANTIC_RANGE =
+'Processando tokens semânticas incrementais...'
+WINDOW_PROCESSING_TYPE_HINT =
+'Processando dicas de lina...'
+WINDOW_INCREASE_UPPER_LIMIT =
+'Aumente o limite superior'
+WINDOW_CLOSE =
+'Fechar'
+WINDOW_SETTING_WS_DIAGNOSTIC =
+'Você pode atrasar ou desativar os diagnósticos do espaço de trabalho nas configurações'
+WINDOW_DONT_SHOW_AGAIN =
+'Não mostre novamente'
+WINDOW_DELAY_WS_DIAGNOSTIC =
+'Diagnóstico de tempo ocioso (atraso de {} segundos)'
+WINDOW_DISABLE_DIAGNOSTIC =
+'Desativa diagnósticos do espaço de trabalho'
+WINDOW_LUA_STATUS_WORKSPACE =
+'Área de trabalho : {}'
+WINDOW_LUA_STATUS_CACHED_FILES =
+'Arquivos em cache: {ast}/{max}'
+WINDOW_LUA_STATUS_MEMORY_COUNT =
+'Uso de memória : {mem:.f}M'
+WINDOW_APPLY_SETTING =
+'Aplicar configuração'
+WINDOW_CHECK_SEMANTIC =
+'Se você estiver usando o tema de cores do market, talvez seja necessário modificar `editor.semanticHighlighting.enabled` para `true` para fazer com tokens semânticas sejam habilitados.'
+WINDOW_TELEMETRY_HINT =
+'Por favor, permita o envio de dados de uso e relatórios de erro anônimos para nos ajudar a melhorar ainda mais essa extensão. Leia nossa política de privacidade [aqui](https://github.com/sumneko/lua-language-server/wiki/Privacy-Policy) .'
+WINDOW_TELEMETRY_ENABLE =
+'Permitir'
+WINDOW_TELEMETRY_DISABLE =
+'Desabilitar'
+WINDOW_CLIENT_NOT_SUPPORT_CONFIG =
+'Seu cliente não suporta configurações de modificação do lado do servidor, modifique manualmente as seguintes configurações:'
+WINDOW_LCONFIG_NOT_SUPPORT_CONFIG=
+'A modificação automática de configurações locais não é suportada atualmente, modifique manualmente as seguintes configurações:'
+WINDOW_MANUAL_CONFIG_ADD =
+'`{key}`: adiciona o elemento `{value:q}` ;'
+WINDOW_MANUAL_CONFIG_SET =
+'`{key}`: defini como `{value:q}` ;'
+WINDOW_MANUAL_CONFIG_PROP =
+'`{key}`: define a propriedade `{prop}` para `{value:q}`;'
+WINDOW_APPLY_WHIT_SETTING =
+'Aplicar e modificar configurações'
+WINDOW_APPLY_WHITOUT_SETTING =
+'Aplicar mas não modificar configurações'
+WINDOW_ASK_APPLY_LIBRARY =
+'Você precisa configurar seu ambiente de trabalho como `{}`?'
-CONFIG_LOAD_FAILED = 'Não é possível ler o arquivo de configurações: {}'
-CONFIG_LOAD_ERROR = 'Configurando o erro de carregamento do arquivo: {}'
-CONFIG_TYPE_ERROR = 'O arquivo de configuração deve estar no formato LUA ou JSON: {}'
+CONFIG_LOAD_FAILED =
+'Não é possível ler o arquivo de configurações: {}'
+CONFIG_LOAD_ERROR =
+'Configurando o erro de carregamento do arquivo: {}'
+CONFIG_TYPE_ERROR =
+'O arquivo de configuração deve estar no formato LUA ou JSON: {}'
-PLUGIN_RUNTIME_ERROR = [[
+PLUGIN_RUNTIME_ERROR =
+[[
Ocorreu um erro no plugin, envie o erro ao autor do plugin.
Por favor, verifique os detalhes na saída ou log.
Caminho do plugin: {}
]]
-PLUGIN_TRUST_LOAD = [[
+PLUGIN_TRUST_LOAD =
+[[
As configurações atuais tentam carregar o plugin neste local: {}
Note que plugins mal-intencionados podem prejudicar seu computador
]]
-PLUGIN_TRUST_YES = [[
+PLUGIN_TRUST_YES =
+[[
Confie e carregue este plugin
]]
-PLUGIN_TRUST_NO = [[
+PLUGIN_TRUST_NO =
+[[
Não carregue este plugin
]]
diff --git a/locale/zh-cn/meta.lua b/locale/zh-cn/meta.lua
index d2fd3c7b..8e7c37e8 100644
--- a/locale/zh-cn/meta.lua
+++ b/locale/zh-cn/meta.lua
@@ -1,55 +1,84 @@
---@diagnostic disable: undefined-global, lowercase-global
-- basic
-arg = '独立版Lua的启动参数。'
-assert = '如果其参数 `v` 的值为假(`nil` 或 `false`), 它就调用 $error; 否则,返回所有的参数。 在错误情况时, `message` 指那个错误对象; 如果不提供这个参数,参数默认为 `"assertion failed!"` 。'
-cgopt.collect = '做一次完整的垃圾收集循环。'
-cgopt.stop = '停止垃圾收集器的运行。'
-cgopt.restart = '重启垃圾收集器的自动运行。'
-cgopt.count = '以 K 字节数为单位返回 Lua 使用的总内存数。'
-cgopt.step = '单步运行垃圾收集器。 步长“大小”由 `arg` 控制。'
-cgopt.setpause = '将 `arg` 设为收集器的 *间歇率* 。'
-cgopt.setstepmul = '将 `arg` 设为收集器的 *步进倍率* 。'
-cgopt.incremental = '改变收集器模式为增量模式。'
-cgopt.generational = '改变收集器模式为分代模式。'
-cgopt.isrunning = '返回表示收集器是否在工作的布尔值。'
-collectgarbage = '这个函数是垃圾收集器的通用接口。 通过参数 opt 它提供了一组不同的功能。'
-dofile = '打开该名字的文件,并执行文件中的 Lua 代码块。 不带参数调用时, `dofile` 执行标准输入的内容(`stdin`)。 返回该代码块的所有返回值。 对于有错误的情况,`dofile` 将错误反馈给调用者 (即,`dofile` 没有运行在保护模式下)。'
-error = [[
+arg =
+'独立版Lua的启动参数。'
+assert =
+'如果其参数 `v` 的值为假(`nil` 或 `false`), 它就调用 $error; 否则,返回所有的参数。 在错误情况时, `message` 指那个错误对象; 如果不提供这个参数,参数默认为 `"assertion failed!"` 。'
+cgopt.collect =
+'做一次完整的垃圾收集循环。'
+cgopt.stop =
+'停止垃圾收集器的运行。'
+cgopt.restart =
+'重启垃圾收集器的自动运行。'
+cgopt.count =
+'以 K 字节数为单位返回 Lua 使用的总内存数。'
+cgopt.step =
+'单步运行垃圾收集器。 步长“大小”由 `arg` 控制。'
+cgopt.setpause =
+'将 `arg` 设为收集器的 *间歇率* 。'
+cgopt.setstepmul =
+'将 `arg` 设为收集器的 *步进倍率* 。'
+cgopt.incremental =
+'改变收集器模式为增量模式。'
+cgopt.generational =
+'改变收集器模式为分代模式。'
+cgopt.isrunning =
+'返回表示收集器是否在工作的布尔值。'
+collectgarbage =
+'这个函数是垃圾收集器的通用接口。 通过参数 opt 它提供了一组不同的功能。'
+dofile =
+'打开该名字的文件,并执行文件中的 Lua 代码块。 不带参数调用时, `dofile` 执行标准输入的内容(`stdin`)。 返回该代码块的所有返回值。 对于有错误的情况,`dofile` 将错误反馈给调用者 (即,`dofile` 没有运行在保护模式下)。'
+error =
+[[
中止上一次保护函数调用, 将错误对象 `message` 返回。 函数 `error` 永远不会返回。
当 `message` 是一个字符串时,通常 `error` 会把一些有关出错位置的信息附加在消息的前头。 level 参数指明了怎样获得出错位置。
]]
-_G = '一个全局变量(非函数), 内部储存有全局环境(参见 §2.2)。 Lua 自己不使用这个变量; 改变这个变量的值不会对任何环境造成影响,反之亦然。'
-getfenv = '返回给定函数的环境。`f` 可以是一个Lua函数,也可是一个表示调用栈层级的数字。'
-getmetatable = '如果 `object` 不包含元表,返回 `nil` 。 否则,如果在该对象的元表中有 `"__metatable"` 域时返回其关联值, 没有时返回该对象的元表。'
-ipairs = [[
+_G =
+'一个全局变量(非函数), 内部储存有全局环境(参见 §2.2)。 Lua 自己不使用这个变量; 改变这个变量的值不会对任何环境造成影响,反之亦然。'
+getfenv =
+'返回给定函数的环境。`f` 可以是一个Lua函数,也可是一个表示调用栈层级的数字。'
+getmetatable =
+'如果 `object` 不包含元表,返回 `nil` 。 否则,如果在该对象的元表中有 `"__metatable"` 域时返回其关联值, 没有时返回该对象的元表。'
+ipairs =
+[[
返回三个值(迭代函数、表 `t` 以及 `0` ), 如此,以下代码
```lua
for i,v in ipairs(t) do body end
```
将迭代键值对 `(1,t[1]) ,(2,t[2]), ...` ,直到第一个空值。
]]
-loadmode.b = '只能是二进制代码块。'
-loadmode.t = '只能是文本代码块。'
-loadmode.bt = '可以是二进制也可以是文本。'
-load['<5.1'] = '使用 `func` 分段加载代码块。 每次调用 `func` 必须返回一个字符串用于连接前文。'
-load['>5.2'] = [[
+loadmode.b =
+'只能是二进制代码块。'
+loadmode.t =
+'只能是文本代码块。'
+loadmode.bt =
+'可以是二进制也可以是文本。'
+load['<5.1'] =
+'使用 `func` 分段加载代码块。 每次调用 `func` 必须返回一个字符串用于连接前文。'
+load['>5.2'] =
+[[
加载一个代码块。
如果 `chunk` 是一个字符串,代码块指这个字符串。 如果 `chunk` 是一个函数, `load` 不断地调用它获取代码块的片断。 每次对 `chunk` 的调用都必须返回一个字符串紧紧连接在上次调用的返回串之后。 当返回空串、`nil`、或是不返回值时,都表示代码块结束。
]]
-loadfile = '从文件 `filename` 或标准输入(如果文件名未提供)中获取代码块。'
-loadstring = '使用给定字符串加载代码块。'
-module = '创建一个模块。'
-next = [[
+loadfile =
+'从文件 `filename` 或标准输入(如果文件名未提供)中获取代码块。'
+loadstring =
+'使用给定字符串加载代码块。'
+module =
+'创建一个模块。'
+next =
+[[
运行程序来遍历表中的所有域。 第一个参数是要遍历的表,第二个参数是表中的某个键。 `next` 返回该键的下一个键及其关联的值。 如果用 `nil` 作为第二个参数调用 `next` 将返回初始键及其关联值。 当以最后一个键去调用,或是以 `nil` 调用一张空表时, `next` 返回 `nil`。 如果不提供第二个参数,将认为它就是 `nil`。 特别指出,你可以用 `next(t)` 来判断一张表是否是空的。
索引在遍历过程中的次序无定义, 即使是数字索引也是这样。 (如果想按数字次序遍历表,可以使用数字形式的 `for` 。)
当在遍历过程中你给表中并不存在的域赋值, `next` 的行为是未定义的。 然而你可以去修改那些已存在的域。 特别指出,你可以清除一些已存在的域。
]]
-pairs = [[
+pairs =
+[[
如果 `t` 有元方法 `__pairs`, 以 `t` 为参数调用它,并返回其返回的前三个值。
否则,返回三个值:`next` 函数, 表 `t`,以及 `nil`。 因此以下代码
@@ -60,138 +89,224 @@ pairs = [[
参见函数 $next 中关于迭代过程中修改表的风险。
]]
-pcall = '传入参数,以 *保护模式* 调用函数 `f` 。 这意味着 `f` 中的任何错误不会抛出; 取而代之的是,`pcall` 会将错误捕获到,并返回一个状态码。 第一个返回值是状态码(一个布尔量), 当没有错误时,其为真。 此时,`pcall` 同样会在状态码后返回所有调用的结果。 在有错误时,`pcall` 返回 `false` 加错误消息。'
-print = '接收任意数量的参数,并将它们的值打印到 `stdout`。 它用 `tostring` 函数将每个参数都转换为字符串。 `print` 不用于做格式化输出。仅作为看一下某个值的快捷方式。 多用于调试。 完整的对输出的控制,请使用 $string.format 以及 $io.write。'
-rawequal = '在不触发任何元方法的情况下 检查 `v1` 是否和 `v2` 相等。 返回一个布尔量。'
-rawget = '在不触发任何元方法的情况下 获取 `table[index]` 的值。 `table` 必须是一张表; `index` 可以是任何值。'
-rawlen = '在不触发任何元方法的情况下 返回对象 `v` 的长度。 `v` 可以是表或字符串。 它返回一个整数。'
-rawset = [[
+pcall =
+'传入参数,以 *保护模式* 调用函数 `f` 。 这意味着 `f` 中的任何错误不会抛出; 取而代之的是,`pcall` 会将错误捕获到,并返回一个状态码。 第一个返回值是状态码(一个布尔量), 当没有错误时,其为真。 此时,`pcall` 同样会在状态码后返回所有调用的结果。 在有错误时,`pcall` 返回 `false` 加错误消息。'
+print =
+'接收任意数量的参数,并将它们的值打印到 `stdout`。 它用 `tostring` 函数将每个参数都转换为字符串。 `print` 不用于做格式化输出。仅作为看一下某个值的快捷方式。 多用于调试。 完整的对输出的控制,请使用 $string.format 以及 $io.write。'
+rawequal =
+'在不触发任何元方法的情况下 检查 `v1` 是否和 `v2` 相等。 返回一个布尔量。'
+rawget =
+'在不触发任何元方法的情况下 获取 `table[index]` 的值。 `table` 必须是一张表; `index` 可以是任何值。'
+rawlen =
+'在不触发任何元方法的情况下 返回对象 `v` 的长度。 `v` 可以是表或字符串。 它返回一个整数。'
+rawset =
+[[
在不触发任何元方法的情况下 将 `table[index]` 设为 `value。` `table` 必须是一张表, `index` 可以是 `nil` 与 `NaN` 之外的任何值。 `value` 可以是任何 Lua 值。
这个函数返回 `table`。
]]
-select = '如果 `index` 是个数字, 那么返回参数中第 `index` 个之后的部分; 负的数字会从后向前索引(`-1` 指最后一个参数)。 否则,`index` 必须是字符串 `"#"`, 此时 `select` 返回参数的个数。'
-setfenv = '设置给定函数的环境。'
-setmetatable = [[
+select =
+'如果 `index` 是个数字, 那么返回参数中第 `index` 个之后的部分; 负的数字会从后向前索引(`-1` 指最后一个参数)。 否则,`index` 必须是字符串 `"#"`, 此时 `select` 返回参数的个数。'
+setfenv =
+'设置给定函数的环境。'
+setmetatable =
+[[
给指定表设置元表。 (你不能在 Lua 中改变其它类型值的元表,那些只能在 C 里做。) 如果 `metatable` 是 `nil`, 将指定表的元表移除。 如果原来那张元表有 `"__metatable"` 域,抛出一个错误。
]]
-tonumber = [[
+tonumber =
+[[
如果调用的时候没有 `base`, `tonumber` 尝试把参数转换为一个数字。 如果参数已经是一个数字,或是一个可以转换为数字的字符串, `tonumber` 就返回这个数字; 否则返回 `nil`。
字符串的转换结果可能是整数也可能是浮点数, 这取决于 Lua 的转换文法(参见 §3.1)。 (字符串可以有前置和后置的空格,可以带符号。)
]]
-tostring = [[
+tostring =
+[[
可以接收任何类型,它将其转换为人可阅读的字符串形式。 浮点数总被转换为浮点数的表现形式(小数点形式或是指数形式)。 (如果想完全控制数字如何被转换,可以使用 $string.format。)
如果 `v` 有 `"__tostring"` 域的元表, `tostring` 会以 `v` 为参数调用它。 并用它的结果作为返回值。
]]
-type = [[
+type =
+[[
将参数的类型编码为一个字符串返回。 函数可能的返回值有 `"nil"` (一个字符串,而不是 `nil` 值), `"number"`, `"string"`, `"boolean"`, `"table"`, `"function"`, `"thread"`, `"userdata"`。
]]
-_VERSION = '一个包含有当前解释器版本号的全局变量(并非函数)。'
-warn = '使用所有参数组成的字符串消息来发送警告。'
-xpcall['=5.1'] = '传入参数,以 *保护模式* 调用函数 `f` 。这个函数和 `pcall` 类似。 不过它可以额外设置一个消息处理器 `err`。'
-xpcall['>5.2'] = '传入参数,以 *保护模式* 调用函数 `f` 。这个函数和 `pcall` 类似。 不过它可以额外设置一个消息处理器 `msgh`。'
-unpack = [[
+_VERSION =
+'一个包含有当前解释器版本号的全局变量(并非函数)。'
+warn =
+'使用所有参数组成的字符串消息来发送警告。'
+xpcall['=5.1'] =
+'传入参数,以 *保护模式* 调用函数 `f` 。这个函数和 `pcall` 类似。 不过它可以额外设置一个消息处理器 `err`。'
+xpcall['>5.2'] =
+'传入参数,以 *保护模式* 调用函数 `f` 。这个函数和 `pcall` 类似。 不过它可以额外设置一个消息处理器 `msgh`。'
+unpack =
+[[
返回给定 `list` 中的所有元素。 改函数等价于
```lua
return list[i], list[i+1], ···, list[j]
```
]]
-bit32 = ''
-bit32.arshift = [[
+bit32 =
+''
+bit32.arshift =
+[[
返回 `x` 向右位移 `disp` 位的结果。`disp` 为负时向左位移。这是算数位移操作,左侧的空位使用 `x` 的高位填充,右侧空位使用 `0` 填充。
]]
-bit32.band = '返回参数按位与的结果。'
-bit32.bnot = [[
+bit32.band =
+'返回参数按位与的结果。'
+bit32.bnot =
+[[
返回 `x` 按位取反的结果。
```lua
-assert(bit32.bnot(x) == (-1 - x) % 2^32)
+assert(bit32.bnot(x) ==
+(-1 - x) % 2^32)
```
]]
-bit32.bor = '返回参数按位或的结果。'
-bit32.btest = '参数按位与的结果不为0时,返回 `true` 。'
-bit32.bxor = '返回参数按位异或的结果。'
-bit32.extract = '返回 `n` 中第 `field` 到第 `field + width - 1` 位组成的结果。'
-bit32.replace = '返回 `v` 的第 `field` 到第 `field + width - 1` 位替换 `n` 的对应位后的结果。'
-bit32.lrotate = '返回 `x` 向左旋转 `disp` 位的结果。`disp` 为负时向右旋转。'
-bit32.lshift = [[
+bit32.bor =
+'返回参数按位或的结果。'
+bit32.btest =
+'参数按位与的结果不为0时,返回 `true` 。'
+bit32.bxor =
+'返回参数按位异或的结果。'
+bit32.extract =
+'返回 `n` 中第 `field` 到第 `field + width - 1` 位组成的结果。'
+bit32.replace =
+'返回 `v` 的第 `field` 到第 `field + width - 1` 位替换 `n` 的对应位后的结果。'
+bit32.lrotate =
+'返回 `x` 向左旋转 `disp` 位的结果。`disp` 为负时向右旋转。'
+bit32.lshift =
+[[
返回 `x` 向左位移 `disp` 位的结果。`disp` 为负时向右位移。空位总是使用 `0` 填充。
```lua
-assert(bit32.lshift(b, disp) == (b * 2^disp) % 2^32)
+assert(bit32.lshift(b, disp) ==
+(b * 2^disp) % 2^32)
```
]]
-bit32.rrotate = '返回 `x` 向右旋转 `disp` 位的结果。`disp` 为负时向左旋转。'
-bit32.rshift = [[
+bit32.rrotate =
+'返回 `x` 向右旋转 `disp` 位的结果。`disp` 为负时向左旋转。'
+bit32.rshift =
+[[
返回 `x` 向右位移 `disp` 位的结果。`disp` 为负时向左位移。空位总是使用 `0` 填充。
```lua
-assert(bit32.lshift(b, disp) == (b * 2^disp) % 2^32)
+assert(bit32.lshift(b, disp) ==
+(b * 2^disp) % 2^32)
```
]]
-coroutine = ''
-coroutine.create = '创建一个主体函数为 `f` 的新协程。 f 必须是一个 Lua 的函数。 返回这个新协程,它是一个类型为 `"thread"` 的对象。'
-coroutine.isyieldable = '如果正在运行的协程可以让出,则返回真。'
-coroutine.isyieldable['>5.4'] = '如果协程 `co` 可以让出,则返回真。`co` 默认为正在运行的协程。'
-coroutine.close = '关闭协程 `co`,并关闭它所有等待 *to-be-closed* 的变量,并将协程状态设为 `dead` 。'
-coroutine.resume = '开始或继续协程 `co` 的运行。'
-coroutine.running = '返回当前正在运行的协程加一个布尔量。 如果当前运行的协程是主线程,其为真。'
-coroutine.status = '以字符串形式返回协程 `co` 的状态。'
-coroutine.wrap = '创建一个主体函数为 `f` 的新协程。 f 必须是一个 Lua 的函数。 返回一个函数, 每次调用该函数都会延续该协程。'
-coroutine.yield = '挂起正在调用的协程的执行。'
-costatus.running = '正在运行。'
-costatus.suspended = '挂起或是还没有开始运行。'
-costatus.normal = '是活动的,但并不在运行。'
-costatus.dead = '运行完主体函数或因错误停止。'
+coroutine =
+''
+coroutine.create =
+'创建一个主体函数为 `f` 的新协程。 f 必须是一个 Lua 的函数。 返回这个新协程,它是一个类型为 `"thread"` 的对象。'
+coroutine.isyieldable =
+'如果正在运行的协程可以让出,则返回真。'
+coroutine.isyieldable['>5.4'] =
+'如果协程 `co` 可以让出,则返回真。`co` 默认为正在运行的协程。'
+coroutine.close =
+'关闭协程 `co`,并关闭它所有等待 *to-be-closed* 的变量,并将协程状态设为 `dead` 。'
+coroutine.resume =
+'开始或继续协程 `co` 的运行。'
+coroutine.running =
+'返回当前正在运行的协程加一个布尔量。 如果当前运行的协程是主线程,其为真。'
+coroutine.status =
+'以字符串形式返回协程 `co` 的状态。'
+coroutine.wrap =
+'创建一个主体函数为 `f` 的新协程。 f 必须是一个 Lua 的函数。 返回一个函数, 每次调用该函数都会延续该协程。'
+coroutine.yield =
+'挂起正在调用的协程的执行。'
+costatus.running =
+'正在运行。'
+costatus.suspended =
+'挂起或是还没有开始运行。'
+costatus.normal =
+'是活动的,但并不在运行。'
+costatus.dead =
+'运行完主体函数或因错误停止。'
-debug = ''
-debug.debug = '进入一个用户交互模式,运行用户输入的每个字符串。'
-debug.getfenv = '返回对象 `o` 的环境。'
-debug.gethook = '返回三个表示线程钩子设置的值: 当前钩子函数,当前钩子掩码,当前钩子计数 。'
-debug.getinfo = '返回关于一个函数信息的表。'
-debug.getlocal['<5.1'] = '返回在栈的 `level` 层处函数的索引为 `index` 的局部变量的名字和值。'
-debug.getlocal['>5.2'] = '返回在栈的 `f` 层处函数的索引为 `index` 的局部变量的名字和值。'
-debug.getmetatable = '返回给定 `value` 的元表。'
-debug.getregistry = '返回注册表。'
-debug.getupvalue = '返回函数 `f` 的第 `up` 个上值的名字和值。'
-debug.getuservalue['<5.3']= '返回关联在 `u` 上的 `Lua` 值。'
-debug.getuservalue['>5.4']= '返回关联在 `u` 上的第 `n` 个 `Lua` 值,以及一个布尔,`false`表示值不存在。'
-debug.setcstacklimit = [[
+debug =
+''
+debug.debug =
+'进入一个用户交互模式,运行用户输入的每个字符串。'
+debug.getfenv =
+'返回对象 `o` 的环境。'
+debug.gethook =
+'返回三个表示线程钩子设置的值: 当前钩子函数,当前钩子掩码,当前钩子计数 。'
+debug.getinfo =
+'返回关于一个函数信息的表。'
+debug.getlocal['<5.1'] =
+'返回在栈的 `level` 层处函数的索引为 `index` 的局部变量的名字和值。'
+debug.getlocal['>5.2'] =
+'返回在栈的 `f` 层处函数的索引为 `index` 的局部变量的名字和值。'
+debug.getmetatable =
+'返回给定 `value` 的元表。'
+debug.getregistry =
+'返回注册表。'
+debug.getupvalue =
+'返回函数 `f` 的第 `up` 个上值的名字和值。'
+debug.getuservalue['<5.3']=
+'返回关联在 `u` 上的 `Lua` 值。'
+debug.getuservalue['>5.4']=
+'返回关联在 `u` 上的第 `n` 个 `Lua` 值,以及一个布尔,`false`表示值不存在。'
+debug.setcstacklimit =
+[[
### **已在 `Lua 5.4.2` 中废弃**
设置新的C栈限制。该限制控制Lua中嵌套调用的深度,以避免堆栈溢出。
如果设置成功,该函数返回之前的限制;否则返回`false`。
]]
-debug.setfenv = '将 `table` 设置为 `object` 的环境。'
-debug.sethook = '将一个函数作为钩子函数设入。'
-debug.setlocal = '将 `value` 赋给 栈上第 `level` 层函数的第 `local` 个局部变量。'
-debug.setmetatable = '将 `value` 的元表设为 `table` (可以是 `nil`)。'
-debug.setupvalue = '将 `value` 设为函数 `f` 的第 `up` 个上值。'
-debug.setuservalue['<5.3']= '将 `value` 设为 `udata` 的关联值。'
-debug.setuservalue['>5.4']= '将 `value` 设为 `udata` 的第 `n` 个关联值。'
-debug.traceback = '返回调用栈的栈回溯信息。 字符串可选项 `message` 被添加在栈回溯信息的开头。'
-debug.upvalueid = '返回指定函数第 `n` 个上值的唯一标识符(一个轻量用户数据)。'
-debug.upvaluejoin = '让 Lua 闭包 `f1` 的第 `n1` 个上值 引用 `Lua` 闭包 `f2` 的第 `n2` 个上值。'
-infowhat.n = '`name` 和 `namewhat`'
-infowhat.S = '`source`,`short_src`,`linedefined`,`lalinedefined`,和 `what`'
-infowhat.l = '`currentline`'
-infowhat.t = '`istailcall`'
-infowhat.u['<5.1'] = '`nups`'
-infowhat.u['>5.2'] = '`nups`、`nparams` 和 `isvararg`'
-infowhat.f = '`func`'
-infowhat.r = '`ftransfer` 和 `ntransfer`'
-infowhat.L = '`activelines`'
-hookmask.c = '每当 Lua 调用一个函数时,调用钩子。'
-hookmask.r = '每当 Lua 从一个函数内返回时,调用钩子。'
-hookmask.l = '每当 Lua 进入新的一行时,调用钩子。'
+debug.setfenv =
+'将 `table` 设置为 `object` 的环境。'
+debug.sethook =
+'将一个函数作为钩子函数设入。'
+debug.setlocal =
+'将 `value` 赋给 栈上第 `level` 层函数的第 `local` 个局部变量。'
+debug.setmetatable =
+'将 `value` 的元表设为 `table` (可以是 `nil`)。'
+debug.setupvalue =
+'将 `value` 设为函数 `f` 的第 `up` 个上值。'
+debug.setuservalue['<5.3']=
+'将 `value` 设为 `udata` 的关联值。'
+debug.setuservalue['>5.4']=
+'将 `value` 设为 `udata` 的第 `n` 个关联值。'
+debug.traceback =
+'返回调用栈的栈回溯信息。 字符串可选项 `message` 被添加在栈回溯信息的开头。'
+debug.upvalueid =
+'返回指定函数第 `n` 个上值的唯一标识符(一个轻量用户数据)。'
+debug.upvaluejoin =
+'让 Lua 闭包 `f1` 的第 `n1` 个上值 引用 `Lua` 闭包 `f2` 的第 `n2` 个上值。'
+infowhat.n =
+'`name` 和 `namewhat`'
+infowhat.S =
+'`source`,`short_src`,`linedefined`,`lalinedefined`,和 `what`'
+infowhat.l =
+'`currentline`'
+infowhat.t =
+'`istailcall`'
+infowhat.u['<5.1'] =
+'`nups`'
+infowhat.u['>5.2'] =
+'`nups`、`nparams` 和 `isvararg`'
+infowhat.f =
+'`func`'
+infowhat.r =
+'`ftransfer` 和 `ntransfer`'
+infowhat.L =
+'`activelines`'
+hookmask.c =
+'每当 Lua 调用一个函数时,调用钩子。'
+hookmask.r =
+'每当 Lua 从一个函数内返回时,调用钩子。'
+hookmask.l =
+'每当 Lua 进入新的一行时,调用钩子。'
-file = ''
-file[':close'] = '关闭 `file`。'
-file[':flush'] = '将写入的数据保存到 `file` 中。'
-file[':lines'] = [[
+file =
+''
+file[':close'] =
+'关闭 `file`。'
+file[':flush'] =
+'将写入的数据保存到 `file` 中。'
+file[':lines'] =
+[[
------
```lua
for c in file:lines(...) do
@@ -199,29 +314,51 @@ for c in file:lines(...) do
end
```
]]
-file[':read'] = '读文件 `file`, 指定的格式决定了要读什么。'
-file[':seek'] = '设置及获取基于文件开头处计算出的位置。'
-file[':setvbuf'] = '设置输出文件的缓冲模式。'
-file[':write'] = '将参数的值逐个写入 `file`。'
-readmode.n = '读取一个数字,根据 Lua 的转换文法返回浮点数或整数。'
-readmode.a = '从当前位置开始读取整个文件。'
-readmode.l = '读取一行并忽略行结束标记。'
-readmode.L = '读取一行并保留行结束标记。'
-seekwhence.set = '基点为 0 (文件开头)。'
-seekwhence.cur = '基点为当前位置。'
-seekwhence['.end'] = '基点为文件尾。'
-vbuf.no = '不缓冲;输出操作立刻生效。'
-vbuf.full = '完全缓冲;只有在缓存满或调用 flush 时才做输出操作。'
-vbuf.line = '行缓冲;输出将缓冲到每次换行前。'
+file[':read'] =
+'读文件 `file`, 指定的格式决定了要读什么。'
+file[':seek'] =
+'设置及获取基于文件开头处计算出的位置。'
+file[':setvbuf'] =
+'设置输出文件的缓冲模式。'
+file[':write'] =
+'将参数的值逐个写入 `file`。'
+readmode.n =
+'读取一个数字,根据 Lua 的转换文法返回浮点数或整数。'
+readmode.a =
+'从当前位置开始读取整个文件。'
+readmode.l =
+'读取一行并忽略行结束标记。'
+readmode.L =
+'读取一行并保留行结束标记。'
+seekwhence.set =
+'基点为 0 (文件开头)。'
+seekwhence.cur =
+'基点为当前位置。'
+seekwhence['.end'] =
+'基点为文件尾。'
+vbuf.no =
+'不缓冲;输出操作立刻生效。'
+vbuf.full =
+'完全缓冲;只有在缓存满或调用 flush 时才做输出操作。'
+vbuf.line =
+'行缓冲;输出将缓冲到每次换行前。'
-io = ''
-io.stdin = '标准输入。'
-io.stdout = '标准输出。'
-io.stderr = '标准错误。'
-io.close = '关闭 `file` 或默认输出文件。'
-io.flush = '将写入的数据保存到默认输出文件中。'
-io.input = '设置 `file` 为默认输入文件。'
-io.lines = [[
+io =
+''
+io.stdin =
+'标准输入。'
+io.stdout =
+'标准输出。'
+io.stderr =
+'标准错误。'
+io.close =
+'关闭 `file` 或默认输出文件。'
+io.flush =
+'将写入的数据保存到默认输出文件中。'
+io.input =
+'设置 `file` 为默认输入文件。'
+io.lines =
+[[
------
```lua
for c in io.lines(filename, ...) do
@@ -229,161 +366,289 @@ for c in io.lines(filename, ...) do
end
```
]]
-io.open = '用字符串 `mode` 指定的模式打开一个文件。'
-io.output = '设置 `file` 为默认输出文件。'
-io.popen = '用一个分离进程开启程序 `prog` 。'
-io.read = '读文件 `file`, 指定的格式决定了要读什么。'
-io.tmpfile = '如果成功,返回一个临时文件的句柄。'
-io.type = '检查 `obj` 是否是合法的文件句柄。'
-io.write = '将参数的值逐个写入默认输出文件。'
-openmode.r = '读模式。'
-openmode.w = '写模式。'
-openmode.a = '追加模式。'
-openmode['.r+'] = '更新模式,所有之前的数据都保留。'
-openmode['.w+'] = '更新模式,所有之前的数据都删除。'
-openmode['.a+'] = '追加更新模式,所有之前的数据都保留,只允许在文件尾部做写入。'
-openmode.rb = '读模式。(二进制方式)'
-openmode.wb = '写模式。(二进制方式)'
-openmode.ab = '追加模式。(二进制方式)'
-openmode['.r+b'] = '更新模式,所有之前的数据都保留。(二进制方式)'
-openmode['.w+b'] = '更新模式,所有之前的数据都删除。(二进制方式)'
-openmode['.a+b'] = '追加更新模式,所有之前的数据都保留,只允许在文件尾部做写入。(二进制方式)'
-popenmode.r = '从这个程序中读取数据。(二进制方式)'
-popenmode.w = '向这个程序写入输入。(二进制方式)'
-filetype.file = '是一个打开的文件句柄。'
-filetype['.closed file'] = '是一个关闭的文件句柄。'
-filetype['.nil'] = '不是文件句柄。'
+io.open =
+'用字符串 `mode` 指定的模式打开一个文件。'
+io.output =
+'设置 `file` 为默认输出文件。'
+io.popen =
+'用一个分离进程开启程序 `prog` 。'
+io.read =
+'读文件 `file`, 指定的格式决定了要读什么。'
+io.tmpfile =
+'如果成功,返回一个临时文件的句柄。'
+io.type =
+'检查 `obj` 是否是合法的文件句柄。'
+io.write =
+'将参数的值逐个写入默认输出文件。'
+openmode.r =
+'读模式。'
+openmode.w =
+'写模式。'
+openmode.a =
+'追加模式。'
+openmode['.r+'] =
+'更新模式,所有之前的数据都保留。'
+openmode['.w+'] =
+'更新模式,所有之前的数据都删除。'
+openmode['.a+'] =
+'追加更新模式,所有之前的数据都保留,只允许在文件尾部做写入。'
+openmode.rb =
+'读模式。(二进制方式)'
+openmode.wb =
+'写模式。(二进制方式)'
+openmode.ab =
+'追加模式。(二进制方式)'
+openmode['.r+b'] =
+'更新模式,所有之前的数据都保留。(二进制方式)'
+openmode['.w+b'] =
+'更新模式,所有之前的数据都删除。(二进制方式)'
+openmode['.a+b'] =
+'追加更新模式,所有之前的数据都保留,只允许在文件尾部做写入。(二进制方式)'
+popenmode.r =
+'从这个程序中读取数据。(二进制方式)'
+popenmode.w =
+'向这个程序写入输入。(二进制方式)'
+filetype.file =
+'是一个打开的文件句柄。'
+filetype['.closed file'] =
+'是一个关闭的文件句柄。'
+filetype['.nil'] =
+'不是文件句柄。'
-math = ''
-math.abs = '返回 `x` 的绝对值。'
-math.acos = '返回 `x` 的反余弦值(用弧度表示)。'
-math.asin = '返回 `x` 的反正弦值(用弧度表示)。'
-math.atan['<5.2'] = '返回 `x` 的反正切值(用弧度表示)。'
-math.atan['>5.3'] = '返回 `y/x` 的反正切值(用弧度表示)。'
-math.atan2 = '返回 `y/x` 的反正切值(用弧度表示)。'
-math.ceil = '返回不小于 `x` 的最小整数值。'
-math.cos = '返回 `x` 的余弦(假定参数是弧度)。'
-math.cosh = '返回 `x` 的双曲余弦(假定参数是弧度)。'
-math.deg = '将角 `x` 从弧度转换为角度。'
-math.exp = '返回 `e^x` 的值 (e 为自然对数的底)。'
-math.floor = '返回不大于 `x` 的最大整数值。'
-math.fmod = '返回 `x` 除以 `y`,将商向零圆整后的余数。'
-math.frexp = '将 `x` 分解为尾数与指数,返回值符合 `x = m * (2 ^ e)` 。`e` 是一个整数,`m` 是 [0.5, 1) 之间的规格化小数 (`x` 为0时 `m` 为0)。'
-math.huge = '一个比任何数字值都大的浮点数。'
-math.ldexp = '返回 `m * (2 ^ e)` 。'
-math.log['<5.1'] = '返回 `x` 的自然对数。'
-math.log['>5.2'] = '回以指定底的 `x` 的对数。'
-math.log10 = '返回 `x` 的以10为底的对数。'
-math.max = '返回参数中最大的值, 大小由 Lua 操作 `<` 决定。'
-math.maxinteger = '最大值的整数。'
-math.min = '返回参数中最小的值, 大小由 Lua 操作 `<` 决定。'
-math.mininteger = '最小值的整数。'
-math.modf = '返回 `x` 的整数部分和小数部分。'
-math.pi = '*π* 的值。'
-math.pow = '返回 `x ^ y` 。'
-math.rad = '将角 `x` 从角度转换为弧度。'
-math.random = [[
+math =
+''
+math.abs =
+'返回 `x` 的绝对值。'
+math.acos =
+'返回 `x` 的反余弦值(用弧度表示)。'
+math.asin =
+'返回 `x` 的反正弦值(用弧度表示)。'
+math.atan['<5.2'] =
+'返回 `x` 的反正切值(用弧度表示)。'
+math.atan['>5.3'] =
+'返回 `y/x` 的反正切值(用弧度表示)。'
+math.atan2 =
+'返回 `y/x` 的反正切值(用弧度表示)。'
+math.ceil =
+'返回不小于 `x` 的最小整数值。'
+math.cos =
+'返回 `x` 的余弦(假定参数是弧度)。'
+math.cosh =
+'返回 `x` 的双曲余弦(假定参数是弧度)。'
+math.deg =
+'将角 `x` 从弧度转换为角度。'
+math.exp =
+'返回 `e^x` 的值 (e 为自然对数的底)。'
+math.floor =
+'返回不大于 `x` 的最大整数值。'
+math.fmod =
+'返回 `x` 除以 `y`,将商向零圆整后的余数。'
+math.frexp =
+'将 `x` 分解为尾数与指数,返回值符合 `x = m * (2 ^ e)` 。`e` 是一个整数,`m` 是 [0.5, 1) 之间的规格化小数 (`x` 为0时 `m` 为0)。'
+math.huge =
+'一个比任何数字值都大的浮点数。'
+math.ldexp =
+'返回 `m * (2 ^ e)` 。'
+math.log['<5.1'] =
+'返回 `x` 的自然对数。'
+math.log['>5.2'] =
+'回以指定底的 `x` 的对数。'
+math.log10 =
+'返回 `x` 的以10为底的对数。'
+math.max =
+'返回参数中最大的值, 大小由 Lua 操作 `<` 决定。'
+math.maxinteger =
+'最大值的整数。'
+math.min =
+'返回参数中最小的值, 大小由 Lua 操作 `<` 决定。'
+math.mininteger =
+'最小值的整数。'
+math.modf =
+'返回 `x` 的整数部分和小数部分。'
+math.pi =
+'*π* 的值。'
+math.pow =
+'返回 `x ^ y` 。'
+math.rad =
+'将角 `x` 从角度转换为弧度。'
+math.random =
+[[
* `math.random()`: 返回 [0,1) 区间内一致分布的浮点伪随机数。
* `math.random(n)`: 返回 [1, n] 区间内一致分布的整数伪随机数。
* `math.random(m, n)`: 返回 [m, n] 区间内一致分布的整数伪随机数。
]]
-math.randomseed['<5.3'] = '把 `x` 设为伪随机数发生器的“种子”: 相同的种子产生相同的随机数列。'
-math.randomseed['>5.4'] = [[
+math.randomseed['<5.3'] =
+'把 `x` 设为伪随机数发生器的“种子”: 相同的种子产生相同的随机数列。'
+math.randomseed['>5.4'] =
+[[
* `math.randomseed(x, y)`: 将 `x` 与 `y` 连接为128位的种子来重新初始化伪随机生成器。
* `math.randomseed(x)`: 等同于 `math.randomseed(x, 0)` 。
* `math.randomseed()`: Generates a seed with a weak attempt for randomness.(不会翻)
]]
-math.sin = '返回 `x` 的正弦值(假定参数是弧度)。'
-math.sinh = '返回 `x` 的双曲正弦值(假定参数是弧度)。'
-math.sqrt = '返回 `x` 的平方根。'
-math.tan = '返回 `x` 的正切值(假定参数是弧度)。'
-math.tanh = '返回 `x` 的双曲正切值(假定参数是弧度)。'
-math.tointeger = '如果 `x` 可以转换为一个整数, 返回该整数。'
-math.type = '如果 `x` 是整数,返回 `"integer"`, 如果它是浮点数,返回 `"float"`, 如果 `x` 不是数字,返回 `nil`。'
-math.ult = '如果整数 `m` 和 `n` 以无符号整数形式比较, `m` 在 `n` 之下,返回布尔真否则返回假。'
+math.sin =
+'返回 `x` 的正弦值(假定参数是弧度)。'
+math.sinh =
+'返回 `x` 的双曲正弦值(假定参数是弧度)。'
+math.sqrt =
+'返回 `x` 的平方根。'
+math.tan =
+'返回 `x` 的正切值(假定参数是弧度)。'
+math.tanh =
+'返回 `x` 的双曲正切值(假定参数是弧度)。'
+math.tointeger =
+'如果 `x` 可以转换为一个整数, 返回该整数。'
+math.type =
+'如果 `x` 是整数,返回 `"integer"`, 如果它是浮点数,返回 `"float"`, 如果 `x` 不是数字,返回 `nil`。'
+math.ult =
+'如果整数 `m` 和 `n` 以无符号整数形式比较, `m` 在 `n` 之下,返回布尔真否则返回假。'
-os = ''
-os.clock = '返回程序使用的按秒计 CPU 时间的近似值。'
-os.date = '返回一个包含日期及时刻的字符串或表。 格式化方法取决于所给字符串 `format`。'
-os.difftime = '返回以秒计算的时刻 `t1` 到 `t2` 的差值。'
-os.execute = '调用系统解释器执行 `command`。'
-os.exit['<5.1'] = '调用 C 函数 `exit` 终止宿主程序。'
-os.exit['>5.2'] = '调用 ISO C 函数 `exit` 终止宿主程序。'
-os.getenv = '返回进程环境变量 `varname` 的值。'
-os.remove = '删除指定名字的文件。'
-os.rename = '将名字为 `oldname` 的文件或目录更名为 `newname`。'
-os.setlocale = '设置程序的当前区域。'
-os.time = '当不传参数时,返回当前时刻。 如果传入一张表,就返回由这张表表示的时刻。'
-os.tmpname = '返回一个可用于临时文件的文件名字符串。'
-osdate.year = '四位数字'
-osdate.month = '1-12'
-osdate.day = '1-31'
-osdate.hour = '0-23'
-osdate.min = '0-59'
-osdate.sec = '0-61'
-osdate.wday = '星期几,1-7,星期天为 1'
-osdate.yday = '当年的第几天,1-366'
-osdate.isdst = '夏令时标记,一个布尔量'
+os =
+''
+os.clock =
+'返回程序使用的按秒计 CPU 时间的近似值。'
+os.date =
+'返回一个包含日期及时刻的字符串或表。 格式化方法取决于所给字符串 `format`。'
+os.difftime =
+'返回以秒计算的时刻 `t1` 到 `t2` 的差值。'
+os.execute =
+'调用系统解释器执行 `command`。'
+os.exit['<5.1'] =
+'调用 C 函数 `exit` 终止宿主程序。'
+os.exit['>5.2'] =
+'调用 ISO C 函数 `exit` 终止宿主程序。'
+os.getenv =
+'返回进程环境变量 `varname` 的值。'
+os.remove =
+'删除指定名字的文件。'
+os.rename =
+'将名字为 `oldname` 的文件或目录更名为 `newname`。'
+os.setlocale =
+'设置程序的当前区域。'
+os.time =
+'当不传参数时,返回当前时刻。 如果传入一张表,就返回由这张表表示的时刻。'
+os.tmpname =
+'返回一个可用于临时文件的文件名字符串。'
+osdate.year =
+'四位数字'
+osdate.month =
+'1-12'
+osdate.day =
+'1-31'
+osdate.hour =
+'0-23'
+osdate.min =
+'0-59'
+osdate.sec =
+'0-61'
+osdate.wday =
+'星期几,1-7,星期天为 1'
+osdate.yday =
+'当年的第几天,1-366'
+osdate.isdst =
+'夏令时标记,一个布尔量'
-package = ''
-require['<5.3'] = '加载一个模块,返回该模块的返回值(`nil`时为`true`)。'
-require['>5.4'] = '加载一个模块,返回该模块的返回值(`nil`时为`true`)与搜索器返回的加载数据。默认搜索器的加载数据指示了加载位置,对于文件来说就是文件路径。'
-package.config = '一个描述有一些为包管理准备的编译期配置信息的串。'
-package.cpath = '这个路径被 `require` 在 C 加载器中做搜索时用到。'
-package.loaded = '用于 `require` 控制哪些模块已经被加载的表。'
-package.loaders = '用于 `require` 控制如何加载模块的表。'
-package.loadlib = '让宿主程序动态链接 C 库 `libname` 。'
-package.path = '这个路径被 `require` 在 Lua 加载器中做搜索时用到。'
-package.preload = '保存有一些特殊模块的加载器。'
-package.searchers = '用于 `require` 控制如何加载模块的表。'
-package.searchpath = '在指定 `path` 中搜索指定的 `name` 。'
-package.seeall = '给 `module` 设置一个元表,该元表的 `__index` 域为全局环境,这样模块便会继承全局环境的值。可作为 `module` 函数的选项。'
+package =
+''
+require['<5.3'] =
+'加载一个模块,返回该模块的返回值(`nil`时为`true`)。'
+require['>5.4'] =
+'加载一个模块,返回该模块的返回值(`nil`时为`true`)与搜索器返回的加载数据。默认搜索器的加载数据指示了加载位置,对于文件来说就是文件路径。'
+package.config =
+'一个描述有一些为包管理准备的编译期配置信息的串。'
+package.cpath =
+'这个路径被 `require` 在 C 加载器中做搜索时用到。'
+package.loaded =
+'用于 `require` 控制哪些模块已经被加载的表。'
+package.loaders =
+'用于 `require` 控制如何加载模块的表。'
+package.loadlib =
+'让宿主程序动态链接 C 库 `libname` 。'
+package.path =
+'这个路径被 `require` 在 Lua 加载器中做搜索时用到。'
+package.preload =
+'保存有一些特殊模块的加载器。'
+package.searchers =
+'用于 `require` 控制如何加载模块的表。'
+package.searchpath =
+'在指定 `path` 中搜索指定的 `name` 。'
+package.seeall =
+'给 `module` 设置一个元表,该元表的 `__index` 域为全局环境,这样模块便会继承全局环境的值。可作为 `module` 函数的选项。'
-string = ''
-string.byte = '返回字符 `s[i]`, `s[i+1]`, ... ,`s[j]` 的内部数字编码。'
-string.char = '接收零或更多的整数。 返回和参数数量相同长度的字符串。 其中每个字符的内部编码值等于对应的参数值。'
-string.dump = '返回包含有以二进制方式表示的(一个 *二进制代码块* )指定函数的字符串。'
-string.find = '查找第一个字符串中匹配到的 `pattern`(参见 §6.4.1)。'
-string.format = '返回不定数量参数的格式化版本,格式化串为第一个参数。'
-string.gmatch = [[
+string =
+''
+string.byte =
+'返回字符 `s[i]`, `s[i+1]`, ... ,`s[j]` 的内部数字编码。'
+string.char =
+'接收零或更多的整数。 返回和参数数量相同长度的字符串。 其中每个字符的内部编码值等于对应的参数值。'
+string.dump =
+'返回包含有以二进制方式表示的(一个 *二进制代码块* )指定函数的字符串。'
+string.find =
+'查找第一个字符串中匹配到的 `pattern`(参见 §6.4.1)。'
+string.format =
+'返回不定数量参数的格式化版本,格式化串为第一个参数。'
+string.gmatch =
+[[
返回一个迭代器函数。 每次调用这个函数都会继续以 `pattern` (参见 §6.4.1) 对 s 做匹配,并返回所有捕获到的值。
下面这个例子会循环迭代字符串 s 中所有的单词, 并逐行打印:
```lua
- s = "hello world from Lua"
+ s =
+"hello world from Lua"
for w in string.gmatch(s, "%a+") do
print(w)
end
```
]]
-string.gsub = '将字符串 s 中,所有的(或是在 n 给出时的前 n 个) pattern (参见 §6.4.1)都替换成 repl ,并返回其副本。'
-string.len = '返回其长度。'
-string.lower = '将其中的大写字符都转为小写后返回其副本。'
-string.match = '在字符串 s 中找到第一个能用 pattern (参见 §6.4.1)匹配到的部分。 如果能找到,match 返回其中的捕获物; 否则返回 nil 。'
-string.pack = '返回一个打包了(即以二进制形式序列化) v1, v2 等值的二进制字符串。 字符串 fmt 为打包格式(参见 §6.4.2)。'
-string.packsize = [[返回以指定格式用 $string.pack 打包的字符串的长度。 格式化字符串中不可以有变长选项 's' 或 'z' (参见 §6.4.2)。]]
-string.rep['<5.1'] = '返回 `n` 个字符串 `s` 连在一起的字符串。 如果 `n` 不是正数则返回空串。'
-string.rep['>5.2'] = '返回 `n` 个字符串 `s` 以字符串 `sep` 为分割符连在一起的字符串。 默认的 `sep` 值为空字符串(即没有分割符)。 如果 `n` 不是正数则返回空串。'
-string.reverse = '返回字符串 s 的翻转串。'
-string.sub = '返回字符串的子串, 该子串从 `i` 开始到 `j` 为止。'
-string.unpack = '返回以格式 fmt (参见 §6.4.2) 打包在字符串 s (参见 string.pack) 中的值。'
-string.upper = '接收一个字符串,将其中的小写字符都转为大写后返回其副本。'
+string.gsub =
+'将字符串 s 中,所有的(或是在 n 给出时的前 n 个) pattern (参见 §6.4.1)都替换成 repl ,并返回其副本。'
+string.len =
+'返回其长度。'
+string.lower =
+'将其中的大写字符都转为小写后返回其副本。'
+string.match =
+'在字符串 s 中找到第一个能用 pattern (参见 §6.4.1)匹配到的部分。 如果能找到,match 返回其中的捕获物; 否则返回 nil 。'
+string.pack =
+'返回一个打包了(即以二进制形式序列化) v1, v2 等值的二进制字符串。 字符串 fmt 为打包格式(参见 §6.4.2)。'
+string.packsize =
+[[返回以指定格式用 $string.pack 打包的字符串的长度。 格式化字符串中不可以有变长选项 's' 或 'z' (参见 §6.4.2)。]]
+string.rep['<5.1'] =
+'返回 `n` 个字符串 `s` 连在一起的字符串。 如果 `n` 不是正数则返回空串。'
+string.rep['>5.2'] =
+'返回 `n` 个字符串 `s` 以字符串 `sep` 为分割符连在一起的字符串。 默认的 `sep` 值为空字符串(即没有分割符)。 如果 `n` 不是正数则返回空串。'
+string.reverse =
+'返回字符串 s 的翻转串。'
+string.sub =
+'返回字符串的子串, 该子串从 `i` 开始到 `j` 为止。'
+string.unpack =
+'返回以格式 fmt (参见 §6.4.2) 打包在字符串 s (参见 string.pack) 中的值。'
+string.upper =
+'接收一个字符串,将其中的小写字符都转为大写后返回其副本。'
-table = ''
-table.concat = '提供一个列表,其所有元素都是字符串或数字,返回字符串 `list[i]..sep..list[i+1] ··· sep..list[j]`。'
-table.insert = '在 `list` 的位置 `pos` 处插入元素 `value`。'
-table.maxn = '返回给定表的最大正数索引,如果表没有正数索引,则返回零。'
-table.move = [[
+table =
+''
+table.concat =
+'提供一个列表,其所有元素都是字符串或数字,返回字符串 `list[i]..sep..list[i+1] ··· sep..list[j]`。'
+table.insert =
+'在 `list` 的位置 `pos` 处插入元素 `value`。'
+table.maxn =
+'返回给定表的最大正数索引,如果表没有正数索引,则返回零。'
+table.move =
+[[
将元素从表 `a1` 移到表 `a2`。
```lua
-a2[t],··· = a1[f],···,a1[e]
+a2[t],··· =
+a1[f],···,a1[e]
return a2
```
]]
-table.pack = '返回用所有参数以键 `1`,`2`, 等填充的新表, 并将 `"n"` 这个域设为参数的总数。'
-table.remove = '移除 `list` 中 `pos` 位置上的元素,并返回这个被移除的值。'
-table.sort = '在表内从 `list[1]` 到 `list[#list]` *原地* 对其间元素按指定次序排序。'
-table.unpack = [[
+table.pack =
+'返回用所有参数以键 `1`,`2`, 等填充的新表, 并将 `"n"` 这个域设为参数的总数。'
+table.remove =
+'移除 `list` 中 `pos` 位置上的元素,并返回这个被移除的值。'
+table.sort =
+'在表内从 `list[1]` 到 `list[#list]` *原地* 对其间元素按指定次序排序。'
+table.unpack =
+[[
返回列表中的元素。 这个函数等价于
```lua
return list[i], list[i+1], ···, list[j]
@@ -391,10 +656,14 @@ table.unpack = [[
i 默认为 1 ,j 默认为 #list。
]]
-utf8 = ''
-utf8.char = '接收零或多个整数, 将每个整数转换成对应的 UTF-8 字节序列,并返回这些序列连接到一起的字符串。'
-utf8.charpattern = '用于精确匹配到一个 UTF-8 字节序列的模式,它假定处理的对象是一个合法的 UTF-8 字符串。'
-utf8.codes = [[
+utf8 =
+''
+utf8.char =
+'接收零或多个整数, 将每个整数转换成对应的 UTF-8 字节序列,并返回这些序列连接到一起的字符串。'
+utf8.charpattern =
+'用于精确匹配到一个 UTF-8 字节序列的模式,它假定处理的对象是一个合法的 UTF-8 字符串。'
+utf8.codes =
+[[
返回一系列的值,可以让
```lua
for p, c in utf8.codes(s) do
@@ -403,6 +672,9 @@ end
```
迭代出字符串 s 中所有的字符。 这里的 p 是位置(按字节数)而 c 是每个字符的编号。 如果处理到一个不合法的字节序列,将抛出一个错误。
]]
-utf8.codepoint = '以整数形式返回 `s` 中 从位置 `i` 到 `j` 间(包括两端) 所有字符的编号。'
-utf8.len = '返回字符串 `s` 中 从位置 `i` 到 `j` 间 (包括两端) UTF-8 字符的个数。'
-utf8.offset = '返回编码在 `s` 中的第 `n` 个字符的开始位置(按字节数) (从位置 `i` 处开始统计)。'
+utf8.codepoint =
+'以整数形式返回 `s` 中 从位置 `i` 到 `j` 间(包括两端) 所有字符的编号。'
+utf8.len =
+'返回字符串 `s` 中 从位置 `i` 到 `j` 间 (包括两端) UTF-8 字符的个数。'
+utf8.offset =
+'返回编码在 `s` 中的第 `n` 个字符的开始位置(按字节数) (从位置 `i` 处开始统计)。'
diff --git a/locale/zh-cn/script.lua b/locale/zh-cn/script.lua
index 7b2f8852..8c944e99 100644
--- a/locale/zh-cn/script.lua
+++ b/locale/zh-cn/script.lua
@@ -1,271 +1,512 @@
-DIAG_LINE_ONLY_SPACE = '只有空格的空行。'
-DIAG_LINE_POST_SPACE = '后置空格。'
-DIAG_UNUSED_LOCAL = '未使用的局部变量 `{}`。'
-DIAG_UNDEF_GLOBAL = '未定义的全局变量 `{}`。'
-DIAG_UNDEF_FIELD = '未定义的属性/字段 `{}`。'
-DIAG_UNDEF_ENV_CHILD = '未定义的变量 `{}`(重载了 `_ENV` )。'
-DIAG_UNDEF_FENV_CHILD = '未定义的变量 `{}`(处于模块中)。'
-DIAG_GLOBAL_IN_NIL_ENV = '不能使用全局变量(`_ENV`被置为了`nil`)。'
-DIAG_GLOBAL_IN_NIL_FENV = '不能使用全局变量(模块被置为了`nil`)。'
-DIAG_UNUSED_LABEL = '未使用的标签 `{}`。'
-DIAG_UNUSED_FUNCTION = '未使用的函数。'
-DIAG_UNUSED_VARARG = '未使用的不定参数。'
-DIAG_REDEFINED_LOCAL = '重定义局部变量 `{}`。'
-DIAG_DUPLICATE_INDEX = '重复的索引 `{}`。'
-DIAG_DUPLICATE_METHOD = '重复的方法 `{}`。'
-DIAG_PREVIOUS_CALL = '会被解释为 `{}{}`。你可能需要加一个 `;`。'
-DIAG_PREFIELD_CALL = '会被解释为 `{}{}`。你可能需要加一个`,`或`;`。'
-DIAG_OVER_MAX_ARGS = '函数只接收 {:d} 个参数,但你传了 {:d} 个。'
-DIAG_OVER_MAX_VALUES = '只有 {} 个变量,但你设置了 {} 个值。'
-DIAG_AMBIGUITY_1 = '会优先运算 `{}`,你可能需要加个括号。'
-DIAG_LOWERCASE_GLOBAL = '首字母小写的全局变量,你是否漏了 `local` 或是有拼写错误?'
-DIAG_EMPTY_BLOCK = '空代码块'
-DIAG_DIAGNOSTICS = 'Lua 诊断'
-DIAG_SYNTAX_CHECK = 'Lua 语法检查'
-DIAG_NEED_VERSION = '在 {} 中是合法的,当前为 {}'
-DIAG_DEFINED_VERSION = '在 {} 中有定义,当前为 {}'
-DIAG_DEFINED_CUSTOM = '在 {} 中有定义'
-DIAG_DUPLICATE_CLASS = '重复定义的 Class `{}`。'
-DIAG_UNDEFINED_CLASS = '未定义的 Class `{}`。'
-DIAG_CYCLIC_EXTENDS = '循环继承。'
-DIAG_INEXISTENT_PARAM = '不存在的参数。'
-DIAG_DUPLICATE_PARAM = '重复的参数。'
-DIAG_NEED_CLASS = '需要先定义 Class 。'
-DIAG_DUPLICATE_SET_FIELD= '重复定义的字段 `{}`。'
-DIAG_SET_CONST = '不能对常量赋值。'
-DIAG_SET_FOR_STATE = '修改了循环变量。'
-DIAG_CODE_AFTER_BREAK = '无法执行到 `break` 后的代码。'
-DIAG_UNBALANCED_ASSIGNMENTS = '由于值的数量不够而被赋值为了 `nil` 。在Lua中, `x, y = 1` 等价于 `x, y = 1, nil` 。'
-DIAG_REQUIRE_LIKE = '你可以在设置中将 `{}` 视为 `require`。'
-DIAG_COSE_NON_OBJECT = '无法 close 此类型的值。(除非给此类型设置 `__close` 元方法)'
-DIAG_COUNT_DOWN_LOOP = '你的意思是 `{}` 吗?'
-DIAG_IMPLICIT_ANY = '无法推测出类型。'
-DIAG_DEPRECATED = '已废弃。'
-DIAG_DIFFERENT_REQUIRES = '使用了不同的名字 require 了同一个文件。'
-DIAG_REDUNDANT_RETURN = '冗余返回。'
-DIAG_AWAIT_IN_SYNC = '只能在标记为异步的函数中调用异步函数。'
-DIAG_NOT_YIELDABLE = '此函数的第 {} 个参数没有被标记为可让出,但是传入了异步函数。(使用 `---@param name async fun()` 来标记为可让出)'
-DIAG_DISCARD_RETURNS = '不能丢弃此函数的返回值。'
+DIAG_LINE_ONLY_SPACE =
+'只有空格的空行。'
+DIAG_LINE_POST_SPACE =
+'后置空格。'
+DIAG_UNUSED_LOCAL =
+'未使用的局部变量 `{}`。'
+DIAG_UNDEF_GLOBAL =
+'未定义的全局变量 `{}`。'
+DIAG_UNDEF_FIELD =
+'未定义的属性/字段 `{}`。'
+DIAG_UNDEF_ENV_CHILD =
+'未定义的变量 `{}`(重载了 `_ENV` )。'
+DIAG_UNDEF_FENV_CHILD =
+'未定义的变量 `{}`(处于模块中)。'
+DIAG_GLOBAL_IN_NIL_ENV =
+'不能使用全局变量(`_ENV`被置为了`nil`)。'
+DIAG_GLOBAL_IN_NIL_FENV =
+'不能使用全局变量(模块被置为了`nil`)。'
+DIAG_UNUSED_LABEL =
+'未使用的标签 `{}`。'
+DIAG_UNUSED_FUNCTION =
+'未使用的函数。'
+DIAG_UNUSED_VARARG =
+'未使用的不定参数。'
+DIAG_REDEFINED_LOCAL =
+'重定义局部变量 `{}`。'
+DIAG_DUPLICATE_INDEX =
+'重复的索引 `{}`。'
+DIAG_DUPLICATE_METHOD =
+'重复的方法 `{}`。'
+DIAG_PREVIOUS_CALL =
+'会被解释为 `{}{}`。你可能需要加一个 `;`。'
+DIAG_PREFIELD_CALL =
+'会被解释为 `{}{}`。你可能需要加一个`,`或`;`。'
+DIAG_OVER_MAX_ARGS =
+'函数只接收 {:d} 个参数,但你传了 {:d} 个。'
+DIAG_OVER_MAX_VALUES =
+'只有 {} 个变量,但你设置了 {} 个值。'
+DIAG_AMBIGUITY_1 =
+'会优先运算 `{}`,你可能需要加个括号。'
+DIAG_LOWERCASE_GLOBAL =
+'首字母小写的全局变量,你是否漏了 `local` 或是有拼写错误?'
+DIAG_EMPTY_BLOCK =
+'空代码块'
+DIAG_DIAGNOSTICS =
+'Lua 诊断'
+DIAG_SYNTAX_CHECK =
+'Lua 语法检查'
+DIAG_NEED_VERSION =
+'在 {} 中是合法的,当前为 {}'
+DIAG_DEFINED_VERSION =
+'在 {} 中有定义,当前为 {}'
+DIAG_DEFINED_CUSTOM =
+'在 {} 中有定义'
+DIAG_DUPLICATE_CLASS =
+'重复定义的 Class `{}`。'
+DIAG_UNDEFINED_CLASS =
+'未定义的 Class `{}`。'
+DIAG_CYCLIC_EXTENDS =
+'循环继承。'
+DIAG_INEXISTENT_PARAM =
+'不存在的参数。'
+DIAG_DUPLICATE_PARAM =
+'重复的参数。'
+DIAG_NEED_CLASS =
+'需要先定义 Class 。'
+DIAG_DUPLICATE_SET_FIELD=
+'重复定义的字段 `{}`。'
+DIAG_SET_CONST =
+'不能对常量赋值。'
+DIAG_SET_FOR_STATE =
+'修改了循环变量。'
+DIAG_CODE_AFTER_BREAK =
+'无法执行到 `break` 后的代码。'
+DIAG_UNBALANCED_ASSIGNMENTS =
+'由于值的数量不够而被赋值为了 `nil` 。在Lua中, `x, y = 1` 等价于 `x, y = 1, nil` 。'
+DIAG_REQUIRE_LIKE =
+'你可以在设置中将 `{}` 视为 `require`。'
+DIAG_COSE_NON_OBJECT =
+'无法 close 此类型的值。(除非给此类型设置 `__close` 元方法)'
+DIAG_COUNT_DOWN_LOOP =
+'你的意思是 `{}` 吗?'
+DIAG_IMPLICIT_ANY =
+'无法推测出类型。'
+DIAG_DEPRECATED =
+'已废弃。'
+DIAG_DIFFERENT_REQUIRES =
+'使用了不同的名字 require 了同一个文件。'
+DIAG_REDUNDANT_RETURN =
+'冗余返回。'
+DIAG_AWAIT_IN_SYNC =
+'只能在标记为异步的函数中调用异步函数。'
+DIAG_NOT_YIELDABLE =
+'此函数的第 {} 个参数没有被标记为可让出,但是传入了异步函数。(使用 `---@param name async fun()` 来标记为可让出)'
+DIAG_DISCARD_RETURNS =
+'不能丢弃此函数的返回值。'
-DIAG_CIRCLE_DOC_CLASS = '循环继承的类。'
-DIAG_DOC_FIELD_NO_CLASS = '字段必须定义在类之后。'
-DIAG_DUPLICATE_DOC_CLASS = '重复定义的类 `{}`。'
-DIAG_DUPLICATE_DOC_FIELD = '重复定义的字段 `{}`。'
-DIAG_DUPLICATE_DOC_PARAM = '重复指向的参数 `{}`。'
-DIAG_UNDEFINED_DOC_CLASS = '未定义的类 `{}`。'
-DIAG_UNDEFINED_DOC_NAME = '未定义的类型或别名 `{}`。'
-DIAG_UNDEFINED_DOC_PARAM = '指向了未定义的参数 `{}`。'
-DIAG_UNKNOWN_DIAG_CODE = '未知的诊断代号 `{}`。'
+DIAG_CIRCLE_DOC_CLASS =
+'循环继承的类。'
+DIAG_DOC_FIELD_NO_CLASS =
+'字段必须定义在类之后。'
+DIAG_DUPLICATE_DOC_CLASS =
+'重复定义的类 `{}`。'
+DIAG_DUPLICATE_DOC_FIELD =
+'重复定义的字段 `{}`。'
+DIAG_DUPLICATE_DOC_PARAM =
+'重复指向的参数 `{}`。'
+DIAG_UNDEFINED_DOC_CLASS =
+'未定义的类 `{}`。'
+DIAG_UNDEFINED_DOC_NAME =
+'未定义的类型或别名 `{}`。'
+DIAG_UNDEFINED_DOC_PARAM =
+'指向了未定义的参数 `{}`。'
+DIAG_UNKNOWN_DIAG_CODE =
+'未知的诊断代号 `{}`。'
-MWS_NOT_SUPPORT = '{} 目前还不支持多工作目录,我可能需要重启才能支持新的工作目录...'
-MWS_RESTART = '重启'
-MWS_NOT_COMPLETE = '工作目录还没有准备好,你可以稍后再试一下...'
-MWS_COMPLETE = '工作目录准备好了,你可以再试一下了...'
-MWS_MAX_PRELOAD = '预加载文件数已达上限({}),你需要手动打开需要加载的文件。'
-MWS_UCONFIG_FAILED = '用户配置保存失败。'
-MWS_UCONFIG_UPDATED = '用户配置已更新。'
-MWS_WCONFIG_UPDATED = '工作区配置已更新。'
+MWS_NOT_SUPPORT =
+'{} 目前还不支持多工作目录,我可能需要重启才能支持新的工作目录...'
+MWS_RESTART =
+'重启'
+MWS_NOT_COMPLETE =
+'工作目录还没有准备好,你可以稍后再试一下...'
+MWS_COMPLETE =
+'工作目录准备好了,你可以再试一下了...'
+MWS_MAX_PRELOAD =
+'预加载文件数已达上限({}),你需要手动打开需要加载的文件。'
+MWS_UCONFIG_FAILED =
+'用户配置保存失败。'
+MWS_UCONFIG_UPDATED =
+'用户配置已更新。'
+MWS_WCONFIG_UPDATED =
+'工作区配置已更新。'
-WORKSPACE_SKIP_LARGE_FILE = '已跳过过大的文件:{}。当前设置的大小限制为:{} KB,该文件大小为:{} KB'
-WORKSPACE_LOADING = '正在加载工作目录'
-WORKSPACE_DIAGNOSTIC = '正在对工作目录进行诊断'
-WORKSPACE_SKIP_HUGE_FILE = '出于性能考虑,已停止对此文件解析:{}'
+WORKSPACE_SKIP_LARGE_FILE =
+'已跳过过大的文件:{}。当前设置的大小限制为:{} KB,该文件大小为:{} KB'
+WORKSPACE_LOADING =
+'正在加载工作目录'
+WORKSPACE_DIAGNOSTIC =
+'正在对工作目录进行诊断'
+WORKSPACE_SKIP_HUGE_FILE =
+'出于性能考虑,已停止对此文件解析:{}'
-PARSER_CRASH = '语法解析崩溃了!遗言:{}'
-PARSER_UNKNOWN = '未知语法错误...'
-PARSER_MISS_NAME = '缺少名称。'
-PARSER_UNKNOWN_SYMBOL = '未知符号`{symbol}`。'
-PARSER_MISS_SYMBOL = '缺少符号`{symbol}`。'
-PARSER_MISS_ESC_X = '必须是2个16进制字符。'
-PARSER_UTF8_SMALL = '至少有1个字符。'
-PARSER_UTF8_MAX = '必须在 {min} 与 {max} 之间。'
-PARSER_ERR_ESC = '错误的转义符。'
-PARSER_MUST_X16 = '必须是16进制字符。'
-PARSER_MISS_EXPONENT = '缺少指数部分。'
-PARSER_MISS_EXP = '缺少表达式。'
-PARSER_MISS_FIELD = '缺少字段/属性名。'
-PARSER_MISS_METHOD = '缺少方法名。'
-PARSER_ARGS_AFTER_DOTS = '`...`必须是最后一个参数。'
-PARSER_KEYWORD = '关键字无法作为名称。'
-PARSER_EXP_IN_ACTION = '该表达式不能作为语句。'
-PARSER_BREAK_OUTSIDE = '`break`必须在循环内部。'
-PARSER_MALFORMED_NUMBER = '无法构成有效数字。'
-PARSER_ACTION_AFTER_RETURN = '`return`之后不能再执行代码。'
-PARSER_ACTION_AFTER_BREAK = '`break`之后不能再执行代码。'
-PARSER_NO_VISIBLE_LABEL = '标签`{label}`不可见。'
-PARSER_REDEFINE_LABEL = '标签`{label}`重复定义。'
-PARSER_UNSUPPORT_SYMBOL = '{version} 不支持该符号。'
-PARSER_UNEXPECT_DOTS = '`...`只能在不定参函数中使用。'
-PARSER_UNEXPECT_SYMBOL = '未知的符号 `{symbol}` 。'
-PARSER_UNKNOWN_TAG = '不支持的属性。'
-PARSER_MULTI_TAG = '只能设置一个属性。'
-PARSER_UNEXPECT_LFUNC_NAME = '局部函数只能使用标识符作为名称。'
-PARSER_UNEXPECT_EFUNC_NAME = '函数作为表达式时不能命名。'
-PARSER_ERR_LCOMMENT_END = '应使用`{symbol}`来关闭多行注释。'
-PARSER_ERR_C_LONG_COMMENT = 'Lua应使用`--[[ ]]`来进行多行注释。'
-PARSER_ERR_LSTRING_END = '应使用`{symbol}`来关闭长字符串。'
-PARSER_ERR_ASSIGN_AS_EQ = '应使用`=`来进行赋值操作。'
-PARSER_ERR_EQ_AS_ASSIGN = '应使用`==`来进行等于判断。'
-PARSER_ERR_UEQ = '应使用`~=`来进行不等于判断。'
-PARSER_ERR_THEN_AS_DO = '应使用`then`。'
-PARSER_ERR_DO_AS_THEN = '应使用`do`。'
-PARSER_MISS_END = '缺少对应的`end`。'
-PARSER_ERR_COMMENT_PREFIX = 'Lua应使用`--`来进行注释。'
-PARSER_MISS_SEP_IN_TABLE = '需要用`,`或`;`进行分割。'
-PARSER_SET_CONST = '不能对常量赋值。'
-PARSER_UNICODE_NAME = '包含了 Unicode 字符。'
-PARSER_ERR_NONSTANDARD_SYMBOL = 'Lua中应使用符号 `{symbol}`。'
-PARSER_MISS_SPACE_BETWEEN = '符号之间必须保留空格'
-PARSER_INDEX_IN_FUNC_NAME = '命名函数的名称中不能使用 `[name]` 形式。'
-PARSER_UNKNOWN_ATTRIBUTE = '局部变量属性应该是 `const` 或 `close`'
+PARSER_CRASH =
+'语法解析崩溃了!遗言:{}'
+PARSER_UNKNOWN =
+'未知语法错误...'
+PARSER_MISS_NAME =
+'缺少名称。'
+PARSER_UNKNOWN_SYMBOL =
+'未知符号`{symbol}`。'
+PARSER_MISS_SYMBOL =
+'缺少符号`{symbol}`。'
+PARSER_MISS_ESC_X =
+'必须是2个16进制字符。'
+PARSER_UTF8_SMALL =
+'至少有1个字符。'
+PARSER_UTF8_MAX =
+'必须在 {min} 与 {max} 之间。'
+PARSER_ERR_ESC =
+'错误的转义符。'
+PARSER_MUST_X16 =
+'必须是16进制字符。'
+PARSER_MISS_EXPONENT =
+'缺少指数部分。'
+PARSER_MISS_EXP =
+'缺少表达式。'
+PARSER_MISS_FIELD =
+'缺少字段/属性名。'
+PARSER_MISS_METHOD =
+'缺少方法名。'
+PARSER_ARGS_AFTER_DOTS =
+'`...`必须是最后一个参数。'
+PARSER_KEYWORD =
+'关键字无法作为名称。'
+PARSER_EXP_IN_ACTION =
+'该表达式不能作为语句。'
+PARSER_BREAK_OUTSIDE =
+'`break`必须在循环内部。'
+PARSER_MALFORMED_NUMBER =
+'无法构成有效数字。'
+PARSER_ACTION_AFTER_RETURN =
+'`return`之后不能再执行代码。'
+PARSER_ACTION_AFTER_BREAK =
+'`break`之后不能再执行代码。'
+PARSER_NO_VISIBLE_LABEL =
+'标签`{label}`不可见。'
+PARSER_REDEFINE_LABEL =
+'标签`{label}`重复定义。'
+PARSER_UNSUPPORT_SYMBOL =
+'{version} 不支持该符号。'
+PARSER_UNEXPECT_DOTS =
+'`...`只能在不定参函数中使用。'
+PARSER_UNEXPECT_SYMBOL =
+'未知的符号 `{symbol}` 。'
+PARSER_UNKNOWN_TAG =
+'不支持的属性。'
+PARSER_MULTI_TAG =
+'只能设置一个属性。'
+PARSER_UNEXPECT_LFUNC_NAME =
+'局部函数只能使用标识符作为名称。'
+PARSER_UNEXPECT_EFUNC_NAME =
+'函数作为表达式时不能命名。'
+PARSER_ERR_LCOMMENT_END =
+'应使用`{symbol}`来关闭多行注释。'
+PARSER_ERR_C_LONG_COMMENT =
+'Lua应使用`--[[ ]]`来进行多行注释。'
+PARSER_ERR_LSTRING_END =
+'应使用`{symbol}`来关闭长字符串。'
+PARSER_ERR_ASSIGN_AS_EQ =
+'应使用`=`来进行赋值操作。'
+PARSER_ERR_EQ_AS_ASSIGN =
+'应使用`==`来进行等于判断。'
+PARSER_ERR_UEQ =
+'应使用`~=`来进行不等于判断。'
+PARSER_ERR_THEN_AS_DO =
+'应使用`then`。'
+PARSER_ERR_DO_AS_THEN =
+'应使用`do`。'
+PARSER_MISS_END =
+'缺少对应的`end`。'
+PARSER_ERR_COMMENT_PREFIX =
+'Lua应使用`--`来进行注释。'
+PARSER_MISS_SEP_IN_TABLE =
+'需要用`,`或`;`进行分割。'
+PARSER_SET_CONST =
+'不能对常量赋值。'
+PARSER_UNICODE_NAME =
+'包含了 Unicode 字符。'
+PARSER_ERR_NONSTANDARD_SYMBOL =
+'Lua中应使用符号 `{symbol}`。'
+PARSER_MISS_SPACE_BETWEEN =
+'符号之间必须保留空格'
+PARSER_INDEX_IN_FUNC_NAME =
+'命名函数的名称中不能使用 `[name]` 形式。'
+PARSER_UNKNOWN_ATTRIBUTE =
+'局部变量属性应该是 `const` 或 `close`'
-PARSER_LUADOC_MISS_CLASS_NAME = '缺少类名称。'
-PARSER_LUADOC_MISS_EXTENDS_SYMBOL = '缺少符号 `:`。'
-PARSER_LUADOC_MISS_CLASS_EXTENDS_NAME = '缺少要继承的类名称。'
-PARSER_LUADOC_MISS_SYMBOL = '缺少符号 `{symbol}`。'
-PARSER_LUADOC_MISS_ARG_NAME = '缺少参数名称。'
-PARSER_LUADOC_MISS_TYPE_NAME = '缺少类型名。'
-PARSER_LUADOC_MISS_ALIAS_NAME = '缺少别名。'
-PARSER_LUADOC_MISS_ALIAS_EXTENDS = '缺少别名定义。'
-PARSER_LUADOC_MISS_PARAM_NAME = '缺少要指向的参数名称。'
-PARSER_LUADOC_MISS_PARAM_EXTENDS = '缺少参数的类型定义。'
-PARSER_LUADOC_MISS_FIELD_NAME = '缺少字段名称。'
-PARSER_LUADOC_MISS_FIELD_EXTENDS = '缺少字段的类型定义。'
-PARSER_LUADOC_MISS_GENERIC_NAME = '缺少泛型名称。'
-PARSER_LUADOC_MISS_GENERIC_EXTENDS_NAME = '缺少泛型要继承的类名称。'
-PARSER_LUADOC_MISS_VARARG_TYPE = '缺少不定参的类型定义。'
-PARSER_LUADOC_MISS_FUN_AFTER_OVERLOAD = '缺少关键字 `fun`。'
-PARSER_LUADOC_MISS_CATE_NAME = '缺少文档类型名称。'
-PARSER_LUADOC_MISS_DIAG_MODE = '缺少诊断模式'
-PARSER_LUADOC_ERROR_DIAG_MODE = '诊断模式不正确'
+PARSER_LUADOC_MISS_CLASS_NAME =
+'缺少类名称。'
+PARSER_LUADOC_MISS_EXTENDS_SYMBOL =
+'缺少符号 `:`。'
+PARSER_LUADOC_MISS_CLASS_EXTENDS_NAME =
+'缺少要继承的类名称。'
+PARSER_LUADOC_MISS_SYMBOL =
+'缺少符号 `{symbol}`。'
+PARSER_LUADOC_MISS_ARG_NAME =
+'缺少参数名称。'
+PARSER_LUADOC_MISS_TYPE_NAME =
+'缺少类型名。'
+PARSER_LUADOC_MISS_ALIAS_NAME =
+'缺少别名。'
+PARSER_LUADOC_MISS_ALIAS_EXTENDS =
+'缺少别名定义。'
+PARSER_LUADOC_MISS_PARAM_NAME =
+'缺少要指向的参数名称。'
+PARSER_LUADOC_MISS_PARAM_EXTENDS =
+'缺少参数的类型定义。'
+PARSER_LUADOC_MISS_FIELD_NAME =
+'缺少字段名称。'
+PARSER_LUADOC_MISS_FIELD_EXTENDS =
+'缺少字段的类型定义。'
+PARSER_LUADOC_MISS_GENERIC_NAME =
+'缺少泛型名称。'
+PARSER_LUADOC_MISS_GENERIC_EXTENDS_NAME =
+'缺少泛型要继承的类名称。'
+PARSER_LUADOC_MISS_VARARG_TYPE =
+'缺少不定参的类型定义。'
+PARSER_LUADOC_MISS_FUN_AFTER_OVERLOAD =
+'缺少关键字 `fun`。'
+PARSER_LUADOC_MISS_CATE_NAME =
+'缺少文档类型名称。'
+PARSER_LUADOC_MISS_DIAG_MODE =
+'缺少诊断模式'
+PARSER_LUADOC_ERROR_DIAG_MODE =
+'诊断模式不正确'
-SYMBOL_ANONYMOUS = '<匿名函数>'
+SYMBOL_ANONYMOUS =
+'<匿名函数>'
-HOVER_VIEW_DOCUMENTS = '查看文档'
+HOVER_VIEW_DOCUMENTS =
+'查看文档'
-HOVER_DOCUMENT_LUA51 = 'http://www.lua.org/manual/5.1/manual.html#{}'
-HOVER_DOCUMENT_LUA52 = 'http://www.lua.org/manual/5.2/manual.html#{}'
-HOVER_DOCUMENT_LUA53 = 'http://cloudwu.github.io/lua53doc/manual.html#{}'
-HOVER_DOCUMENT_LUA54 = 'http://www.lua.org/manual/5.4/manual.html#{}'
-HOVER_DOCUMENT_LUAJIT = 'http://www.lua.org/manual/5.1/manual.html#{}'
+HOVER_DOCUMENT_LUA51 =
+'http://www.lua.org/manual/5.1/manual.html#{}'
+HOVER_DOCUMENT_LUA52 =
+'http://www.lua.org/manual/5.2/manual.html#{}'
+HOVER_DOCUMENT_LUA53 =
+'http://cloudwu.github.io/lua53doc/manual.html#{}'
+HOVER_DOCUMENT_LUA54 =
+'http://www.lua.org/manual/5.4/manual.html#{}'
+HOVER_DOCUMENT_LUAJIT =
+'http://www.lua.org/manual/5.1/manual.html#{}'
-HOVER_NATIVE_DOCUMENT_LUA51 = 'command:extension.lua.doc?["en-us/51/manual.html/{}"]'
-HOVER_NATIVE_DOCUMENT_LUA52 = 'command:extension.lua.doc?["en-us/52/manual.html/{}"]'
-HOVER_NATIVE_DOCUMENT_LUA53 = 'command:extension.lua.doc?["zh-cn/53/manual.html/{}"]'
-HOVER_NATIVE_DOCUMENT_LUA54 = 'command:extension.lua.doc?["en-us/54/manual.html/{}"]'
-HOVER_NATIVE_DOCUMENT_LUAJIT = 'command:extension.lua.doc?["en-us/51/manual.html/{}"]'
+HOVER_NATIVE_DOCUMENT_LUA51 =
+'command:extension.lua.doc?["en-us/51/manual.html/{}"]'
+HOVER_NATIVE_DOCUMENT_LUA52 =
+'command:extension.lua.doc?["en-us/52/manual.html/{}"]'
+HOVER_NATIVE_DOCUMENT_LUA53 =
+'command:extension.lua.doc?["zh-cn/53/manual.html/{}"]'
+HOVER_NATIVE_DOCUMENT_LUA54 =
+'command:extension.lua.doc?["en-us/54/manual.html/{}"]'
+HOVER_NATIVE_DOCUMENT_LUAJIT =
+'command:extension.lua.doc?["en-us/51/manual.html/{}"]'
-HOVER_MULTI_PROTOTYPE = '({} 个原型)'
-HOVER_STRING_BYTES = '{} 个字节'
-HOVER_STRING_CHARACTERS = '{} 个字节,{} 个字符'
-HOVER_MULTI_DEF_PROTO = '({} 个定义,{} 个原型)'
-HOVER_MULTI_PROTO_NOT_FUNC = '({} 个非函数定义)'
+HOVER_MULTI_PROTOTYPE =
+'({} 个原型)'
+HOVER_STRING_BYTES =
+'{} 个字节'
+HOVER_STRING_CHARACTERS =
+'{} 个字节,{} 个字符'
+HOVER_MULTI_DEF_PROTO =
+'({} 个定义,{} 个原型)'
+HOVER_MULTI_PROTO_NOT_FUNC =
+'({} 个非函数定义)'
-HOVER_USE_LUA_PATH = '(搜索路径: `{}`)'
-HOVER_EXTENDS = '展开为 {}'
-HOVER_TABLE_TIME_UP = '出于性能考虑,已禁用了部分类型推断。'
-HOVER_WS_LOADING = '正在加载工作目录:{} / {}'
+HOVER_USE_LUA_PATH =
+'(搜索路径: `{}`)'
+HOVER_EXTENDS =
+'展开为 {}'
+HOVER_TABLE_TIME_UP =
+'出于性能考虑,已禁用了部分类型推断。'
+HOVER_WS_LOADING =
+'正在加载工作目录:{} / {}'
-ACTION_DISABLE_DIAG = '在工作区禁用诊断 ({})。'
-ACTION_MARK_GLOBAL = '标记 `{}` 为已定义的全局变量。'
-ACTION_REMOVE_SPACE = '清除所有后置空格。'
-ACTION_ADD_SEMICOLON = '添加 `;` 。'
-ACTION_ADD_BRACKETS = '添加括号。'
-ACTION_RUNTIME_VERSION = '修改运行版本为 {} 。'
-ACTION_OPEN_LIBRARY = '加载 {} 中的全局变量。'
-ACTION_ADD_DO_END = '添加 `do ... end` 。'
-ACTION_FIX_LCOMMENT_END = '改用正确的多行注释关闭符号。'
-ACTION_ADD_LCOMMENT_END = '关闭多行注释。'
-ACTION_FIX_C_LONG_COMMENT = '修改为 Lua 的多行注释格式。'
-ACTION_FIX_LSTRING_END = '改用正确的长字符串关闭符号。'
-ACTION_ADD_LSTRING_END = '关闭长字符串。'
-ACTION_FIX_ASSIGN_AS_EQ = '改为 `=` 。'
-ACTION_FIX_EQ_AS_ASSIGN = '改为 `==` 。'
-ACTION_FIX_UEQ = '改为 `~=` 。'
-ACTION_FIX_THEN_AS_DO = '改为 `then` 。'
-ACTION_FIX_DO_AS_THEN = '改为 `do` 。'
-ACTION_ADD_END = '添加 `end` (根据缩进推测添加位置)。'
-ACTION_FIX_COMMENT_PREFIX = '改为 `--` 。'
-ACTION_FIX_NONSTANDARD_SYMBOL = '改为 `{symbol}`'
-ACTION_RUNTIME_UNICODE_NAME = '允许使用 Unicode 字符。'
-ACTION_SWAP_PARAMS = '将其改为 `{node}` 的第 {index} 个参数'
-ACTION_FIX_INSERT_SPACE = '插入空格'
-ACTION_JSON_TO_LUA = '把 JSON 转成 Lua'
-ACTION_DISABLE_DIAG_LINE= '在此行禁用诊断 ({})。'
-ACTION_DISABLE_DIAG_FILE= '在此文件禁用诊断 ({})。'
-ACTION_MARK_ASYNC = '将当前函数标记为异步。'
+ACTION_DISABLE_DIAG =
+'在工作区禁用诊断 ({})。'
+ACTION_MARK_GLOBAL =
+'标记 `{}` 为已定义的全局变量。'
+ACTION_REMOVE_SPACE =
+'清除所有后置空格。'
+ACTION_ADD_SEMICOLON =
+'添加 `;` 。'
+ACTION_ADD_BRACKETS =
+'添加括号。'
+ACTION_RUNTIME_VERSION =
+'修改运行版本为 {} 。'
+ACTION_OPEN_LIBRARY =
+'加载 {} 中的全局变量。'
+ACTION_ADD_DO_END =
+'添加 `do ... end` 。'
+ACTION_FIX_LCOMMENT_END =
+'改用正确的多行注释关闭符号。'
+ACTION_ADD_LCOMMENT_END =
+'关闭多行注释。'
+ACTION_FIX_C_LONG_COMMENT =
+'修改为 Lua 的多行注释格式。'
+ACTION_FIX_LSTRING_END =
+'改用正确的长字符串关闭符号。'
+ACTION_ADD_LSTRING_END =
+'关闭长字符串。'
+ACTION_FIX_ASSIGN_AS_EQ =
+'改为 `=` 。'
+ACTION_FIX_EQ_AS_ASSIGN =
+'改为 `==` 。'
+ACTION_FIX_UEQ =
+'改为 `~=` 。'
+ACTION_FIX_THEN_AS_DO =
+'改为 `then` 。'
+ACTION_FIX_DO_AS_THEN =
+'改为 `do` 。'
+ACTION_ADD_END =
+'添加 `end` (根据缩进推测添加位置)。'
+ACTION_FIX_COMMENT_PREFIX =
+'改为 `--` 。'
+ACTION_FIX_NONSTANDARD_SYMBOL =
+'改为 `{symbol}`'
+ACTION_RUNTIME_UNICODE_NAME =
+'允许使用 Unicode 字符。'
+ACTION_SWAP_PARAMS =
+'将其改为 `{node}` 的第 {index} 个参数'
+ACTION_FIX_INSERT_SPACE =
+'插入空格'
+ACTION_JSON_TO_LUA =
+'把 JSON 转成 Lua'
+ACTION_DISABLE_DIAG_LINE=
+'在此行禁用诊断 ({})。'
+ACTION_DISABLE_DIAG_FILE=
+'在此文件禁用诊断 ({})。'
+ACTION_MARK_ASYNC =
+'将当前函数标记为异步。'
-COMMAND_DISABLE_DIAG = '禁用诊断'
-COMMAND_MARK_GLOBAL = '标记全局变量'
-COMMAND_REMOVE_SPACE = '清除所有后置空格'
-COMMAND_ADD_BRACKETS = '添加括号'
-COMMAND_RUNTIME_VERSION = '修改运行版本'
-COMMAND_OPEN_LIBRARY = '加载第三方库中的全局变量'
-COMMAND_UNICODE_NAME = '允许使用 Unicode 字符'
-COMMAND_JSON_TO_LUA = 'JSON 转 Lua'
-COMMAND_JSON_TO_LUA_FAILED = 'JSON 转 Lua 失败:{}'
+COMMAND_DISABLE_DIAG =
+'禁用诊断'
+COMMAND_MARK_GLOBAL =
+'标记全局变量'
+COMMAND_REMOVE_SPACE =
+'清除所有后置空格'
+COMMAND_ADD_BRACKETS =
+'添加括号'
+COMMAND_RUNTIME_VERSION =
+'修改运行版本'
+COMMAND_OPEN_LIBRARY =
+'加载第三方库中的全局变量'
+COMMAND_UNICODE_NAME =
+'允许使用 Unicode 字符'
+COMMAND_JSON_TO_LUA =
+'JSON 转 Lua'
+COMMAND_JSON_TO_LUA_FAILED =
+'JSON 转 Lua 失败:{}'
-COMPLETION_IMPORT_FROM = '从 {} 中导入'
-COMPLETION_DISABLE_AUTO_REQUIRE = '禁用自动require'
-COMPLETION_ASK_AUTO_REQUIRE = '在文件顶部添加代码 require 此文件?'
+COMPLETION_IMPORT_FROM =
+'从 {} 中导入'
+COMPLETION_DISABLE_AUTO_REQUIRE =
+'禁用自动require'
+COMPLETION_ASK_AUTO_REQUIRE =
+'在文件顶部添加代码 require 此文件?'
-DEBUG_MEMORY_LEAK = '{} 很抱歉发生了严重的内存泄漏,语言服务即将重启。'
-DEBUG_RESTART_NOW = '立即重启'
+DEBUG_MEMORY_LEAK =
+'{} 很抱歉发生了严重的内存泄漏,语言服务即将重启。'
+DEBUG_RESTART_NOW =
+'立即重启'
-WINDOW_COMPILING = '正在编译'
-WINDOW_DIAGNOSING = '正在诊断'
-WINDOW_INITIALIZING = '正在初始化...'
-WINDOW_PROCESSING_HOVER = '正在处理悬浮提示...'
-WINDOW_PROCESSING_DEFINITION = '正在处理转到定义...'
-WINDOW_PROCESSING_REFERENCE = '正在处理转到引用...'
-WINDOW_PROCESSING_RENAME = '正在处理重命名...'
-WINDOW_PROCESSING_COMPLETION = '正在处理自动完成...'
-WINDOW_PROCESSING_SIGNATURE = '正在处理参数提示...'
-WINDOW_PROCESSING_SYMBOL = '正在处理文件符号...'
-WINDOW_PROCESSING_WS_SYMBOL = '正在处理工作区符号...'
-WINDOW_PROCESSING_SEMANTIC_FULL = '正在处理全量语义着色...'
-WINDOW_PROCESSING_SEMANTIC_RANGE = '正在处理差量语义着色...'
-WINDOW_PROCESSING_HINT = '正在处理内联提示...'
-WINDOW_INCREASE_UPPER_LIMIT = '增加上限'
-WINDOW_CLOSE = '关闭'
-WINDOW_SETTING_WS_DIAGNOSTIC = '你可以在设置中延迟或禁用工作目录诊断'
-WINDOW_DONT_SHOW_AGAIN = '不再提示'
-WINDOW_DELAY_WS_DIAGNOSTIC = '空闲时诊断(延迟{}秒)'
-WINDOW_DISABLE_DIAGNOSTIC = '禁用工作区诊断'
-WINDOW_LUA_STATUS_WORKSPACE = '工作区:{}'
-WINDOW_LUA_STATUS_CACHED_FILES = '已缓存文件:{ast}/{max}'
-WINDOW_LUA_STATUS_MEMORY_COUNT = '内存占用:{mem:.f}M'
-WINDOW_APPLY_SETTING = '应用设置'
-WINDOW_CHECK_SEMANTIC = '如果你正在使用市场中的颜色主题,你可能需要同时修改 `editor.semanticHighlighting.enabled` 选项为 `true` 才会使语义着色生效。'
-WINDOW_TELEMETRY_HINT = '请允许发送匿名的使用数据与错误报告,帮助我们进一步完善此插件。在[此处](https://github.com/sumneko/lua-language-server/wiki/%E9%9A%90%E7%A7%81%E5%A3%B0%E6%98%8E)阅读我们的隐私声明。'
-WINDOW_TELEMETRY_ENABLE = '允许'
-WINDOW_TELEMETRY_DISABLE = '禁止'
-WINDOW_CLIENT_NOT_SUPPORT_CONFIG = '你的客户端不支持从服务侧修改设置,请手动修改如下设置:'
-WINDOW_LCONFIG_NOT_SUPPORT_CONFIG= '暂不支持自动修改本地设置,请手动修改如下设置:'
-WINDOW_MANUAL_CONFIG_ADD = '为 `{key}` 添加值 `{value:q}`;'
-WINDOW_MANUAL_CONFIG_SET = '将 `{key}` 的值设置为 `{value:q}`;'
-WINDOW_MANUAL_CONFIG_PROP = '将 `{key}` 的属性 `{prop}` 设置为 `{value:q}`;'
-WINDOW_APPLY_WHIT_SETTING = '应用并修改设置'
-WINDOW_APPLY_WHITOUT_SETTING = '应用但不修改设置'
-WINDOW_ASK_APPLY_LIBRARY = '是否需要将你的工作环境配置为 `{}` ?'
+WINDOW_COMPILING =
+'正在编译'
+WINDOW_DIAGNOSING =
+'正在诊断'
+WINDOW_INITIALIZING =
+'正在初始化...'
+WINDOW_PROCESSING_HOVER =
+'正在处理悬浮提示...'
+WINDOW_PROCESSING_DEFINITION =
+'正在处理转到定义...'
+WINDOW_PROCESSING_REFERENCE =
+'正在处理转到引用...'
+WINDOW_PROCESSING_RENAME =
+'正在处理重命名...'
+WINDOW_PROCESSING_COMPLETION =
+'正在处理自动完成...'
+WINDOW_PROCESSING_SIGNATURE =
+'正在处理参数提示...'
+WINDOW_PROCESSING_SYMBOL =
+'正在处理文件符号...'
+WINDOW_PROCESSING_WS_SYMBOL =
+'正在处理工作区符号...'
+WINDOW_PROCESSING_SEMANTIC_FULL =
+'正在处理全量语义着色...'
+WINDOW_PROCESSING_SEMANTIC_RANGE =
+'正在处理差量语义着色...'
+WINDOW_PROCESSING_HINT =
+'正在处理内联提示...'
+WINDOW_INCREASE_UPPER_LIMIT =
+'增加上限'
+WINDOW_CLOSE =
+'关闭'
+WINDOW_SETTING_WS_DIAGNOSTIC =
+'你可以在设置中延迟或禁用工作目录诊断'
+WINDOW_DONT_SHOW_AGAIN =
+'不再提示'
+WINDOW_DELAY_WS_DIAGNOSTIC =
+'空闲时诊断(延迟{}秒)'
+WINDOW_DISABLE_DIAGNOSTIC =
+'禁用工作区诊断'
+WINDOW_LUA_STATUS_WORKSPACE =
+'工作区:{}'
+WINDOW_LUA_STATUS_CACHED_FILES =
+'已缓存文件:{ast}/{max}'
+WINDOW_LUA_STATUS_MEMORY_COUNT =
+'内存占用:{mem:.f}M'
+WINDOW_APPLY_SETTING =
+'应用设置'
+WINDOW_CHECK_SEMANTIC =
+'如果你正在使用市场中的颜色主题,你可能需要同时修改 `editor.semanticHighlighting.enabled` 选项为 `true` 才会使语义着色生效。'
+WINDOW_TELEMETRY_HINT =
+'请允许发送匿名的使用数据与错误报告,帮助我们进一步完善此插件。在[此处](https://github.com/sumneko/lua-language-server/wiki/%E9%9A%90%E7%A7%81%E5%A3%B0%E6%98%8E)阅读我们的隐私声明。'
+WINDOW_TELEMETRY_ENABLE =
+'允许'
+WINDOW_TELEMETRY_DISABLE =
+'禁止'
+WINDOW_CLIENT_NOT_SUPPORT_CONFIG =
+'你的客户端不支持从服务侧修改设置,请手动修改如下设置:'
+WINDOW_LCONFIG_NOT_SUPPORT_CONFIG=
+'暂不支持自动修改本地设置,请手动修改如下设置:'
+WINDOW_MANUAL_CONFIG_ADD =
+'为 `{key}` 添加值 `{value:q}`;'
+WINDOW_MANUAL_CONFIG_SET =
+'将 `{key}` 的值设置为 `{value:q}`;'
+WINDOW_MANUAL_CONFIG_PROP =
+'将 `{key}` 的属性 `{prop}` 设置为 `{value:q}`;'
+WINDOW_APPLY_WHIT_SETTING =
+'应用并修改设置'
+WINDOW_APPLY_WHITOUT_SETTING =
+'应用但不修改设置'
+WINDOW_ASK_APPLY_LIBRARY =
+'是否需要将你的工作环境配置为 `{}` ?'
-CONFIG_LOAD_FAILED = '无法读取设置文件:{}'
-CONFIG_LOAD_ERROR = '设置文件加载错误:{}'
-CONFIG_TYPE_ERROR = '设置文件必须是lua或json格式:{}'
+CONFIG_LOAD_FAILED =
+'无法读取设置文件:{}'
+CONFIG_LOAD_ERROR =
+'设置文件加载错误:{}'
+CONFIG_TYPE_ERROR =
+'设置文件必须是lua或json格式:{}'
-PLUGIN_RUNTIME_ERROR = [[
+PLUGIN_RUNTIME_ERROR =
+[[
插件发生错误,请汇报给插件作者。
请在输出或日志中查看详细信息。
插件路径:{}
]]
-PLUGIN_TRUST_LOAD = [[
+PLUGIN_TRUST_LOAD =
+[[
当前设置试图加载位于此位置的插件:{}
注意,恶意的插件可能会危害您的电脑
]]
-PLUGIN_TRUST_YES = [[
+PLUGIN_TRUST_YES =
+[[
信任并加载插件
]]
-PLUGIN_TRUST_NO = [[
+PLUGIN_TRUST_NO =
+[[
不要加载此插件
]]
diff --git a/locale/zh-cn/setting.lua b/locale/zh-cn/setting.lua
index 2a56d287..7323d68e 100644
--- a/locale/zh-cn/setting.lua
+++ b/locale/zh-cn/setting.lua
@@ -1,14 +1,18 @@
---@diagnostic disable: undefined-global
-config.runtime.version = "Lua运行版本。"
-config.runtime.path = [[
+config.runtime.version =
+"Lua运行版本。"
+config.runtime.path =
+[[
当使用 `require` 时,如何根据输入的名字来查找文件。
此选项设置为 `?/init.lua` 意味着当你输入 `require 'myfile'` 时,会从已加载的文件中搜索 `{workspace}/myfile/init.lua`。
当 `runtime.pathStrict` 设置为 `false` 时,还会尝试搜索 `${workspace}/**/myfile/init.lua`。
如果你想要加载工作区以外的文件,你需要先设置 `Lua.workspace.library`。
]]
-config.runtime.pathStrict = '启用后 `runtime.path` 将只搜索第一层目录,见 `runtime.path` 的说明。'
-config.runtime.special = [[将自定义全局变量视为一些特殊的内置变量,语言服务将提供特殊的支持。
+config.runtime.pathStrict =
+'启用后 `runtime.path` 将只搜索第一层目录,见 `runtime.path` 的说明。'
+config.runtime.special =
+[[将自定义全局变量视为一些特殊的内置变量,语言服务将提供特殊的支持。
下面这个例子表示将 `include` 视为 `require` 。
```json
"Lua.runtime.special" : {
@@ -16,40 +20,64 @@ config.runtime.special = [[将自定义全局变量视为一些特殊
}
```
]]
-config.runtime.unicodeName = "允许在名字中使用 Unicode 字符。"
-config.runtime.nonstandardSymbol = "支持非标准的符号。请务必确认你的运行环境支持这些符号。"
-config.runtime.plugin = "插件路径,请查阅[文档](https://github.com/sumneko/lua-language-server/wiki/Plugin)了解用法。"
-config.runtime.fileEncoding = "文件编码,`ansi` 选项只在 `Windows` 平台下有效。"
-config.runtime.builtin = [[
+config.runtime.unicodeName =
+"允许在名字中使用 Unicode 字符。"
+config.runtime.nonstandardSymbol =
+"支持非标准的符号。请务必确认你的运行环境支持这些符号。"
+config.runtime.plugin =
+"插件路径,请查阅[文档](https://github.com/sumneko/lua-language-server/wiki/Plugin)了解用法。"
+config.runtime.fileEncoding =
+"文件编码,`ansi` 选项只在 `Windows` 平台下有效。"
+config.runtime.builtin =
+[[
调整内置库的启用状态,你可以根据实际运行环境禁用掉不存在的库(或重新定义)。
* `default`: 表示库会根据运行版本启用或禁用
* `enable`: 总是启用
* `disable`: 总是禁用
]]
-config.diagnostics.enable = "启用诊断。"
-config.diagnostics.disable = "禁用的诊断(使用浮框括号内的代码)。"
-config.diagnostics.globals = "已定义的全局变量。"
-config.diagnostics.severity = "修改诊断等级。"
-config.diagnostics.neededFileStatus = [[
+config.diagnostics.enable =
+"启用诊断。"
+config.diagnostics.disable =
+"禁用的诊断(使用浮框括号内的代码)。"
+config.diagnostics.globals =
+"已定义的全局变量。"
+config.diagnostics.severity =
+"修改诊断等级。"
+config.diagnostics.neededFileStatus =
+[[
* Opened: 只诊断打开的文件
* Any: 诊断任何文件
* Disable: 禁用此诊断
]]
-config.diagnostics.workspaceDelay = "进行工作区诊断的延迟(毫秒)。当你启动工作区,或编辑了任意文件后,将会在后台对整个工作区进行重新诊断。设置为负数可以禁用工作区诊断。"
-config.diagnostics.workspaceRate = "工作区诊断的运行速率(百分比)。降低该值会减少CPU占用,但是也会降低工作区诊断的速度。你当前正在编辑的文件的诊断总是全速完成,不受该选项影响。"
-config.diagnostics.libraryFiles = "如何诊断通过 `Lua.workspace.library` 加载的文件。"
-config.diagnostics.ignoredFiles = "如何诊断被忽略的文件。"
-config.diagnostics.files.Enable = "总是诊断这些文件。"
-config.diagnostics.files.Opened = "只有打开这些文件时才会诊断。"
-config.diagnostics.files.Disable = "不诊断这些文件。"
-config.workspace.ignoreDir = "忽略的文件与目录(使用 `.gitignore` 语法)。"
-config.workspace.ignoreSubmodules = "忽略子模块。"
-config.workspace.useGitIgnore = "忽略 `.gitignore` 中列举的文件。"
-config.workspace.maxPreload = "最大预加载文件数。"
-config.workspace.preloadFileSize = "预加载时跳过大小大于该值(KB)的文件。"
-config.workspace.library = "除了当前工作区以外,还会从哪些目录中加载文件。这些目录中的文件将被视作外部提供的代码库,部分操作(如重命名字段)不会修改这些文件。"
-config.workspace.checkThirdParty = [[
+config.diagnostics.workspaceDelay =
+"进行工作区诊断的延迟(毫秒)。当你启动工作区,或编辑了任意文件后,将会在后台对整个工作区进行重新诊断。设置为负数可以禁用工作区诊断。"
+config.diagnostics.workspaceRate =
+"工作区诊断的运行速率(百分比)。降低该值会减少CPU占用,但是也会降低工作区诊断的速度。你当前正在编辑的文件的诊断总是全速完成,不受该选项影响。"
+config.diagnostics.libraryFiles =
+"如何诊断通过 `Lua.workspace.library` 加载的文件。"
+config.diagnostics.ignoredFiles =
+"如何诊断被忽略的文件。"
+config.diagnostics.files.Enable =
+"总是诊断这些文件。"
+config.diagnostics.files.Opened =
+"只有打开这些文件时才会诊断。"
+config.diagnostics.files.Disable =
+"不诊断这些文件。"
+config.workspace.ignoreDir =
+"忽略的文件与目录(使用 `.gitignore` 语法)。"
+config.workspace.ignoreSubmodules =
+"忽略子模块。"
+config.workspace.useGitIgnore =
+"忽略 `.gitignore` 中列举的文件。"
+config.workspace.maxPreload =
+"最大预加载文件数。"
+config.workspace.preloadFileSize =
+"预加载时跳过大小大于该值(KB)的文件。"
+config.workspace.library =
+"除了当前工作区以外,还会从哪些目录中加载文件。这些目录中的文件将被视作外部提供的代码库,部分操作(如重命名字段)不会修改这些文件。"
+config.workspace.checkThirdParty =
+[[
自动检测与适配第三方库,目前支持的库为:
* OpenResty
@@ -59,84 +87,163 @@ config.workspace.checkThirdParty = [[
* skynet
* Jass
]]
-config.workspace.userThirdParty = '在这里添加私有的第三方库适配文件路径,请参考内置的[配置文件路径](https://github.com/sumneko/lua-language-server/tree/master/meta/3rd)'
-config.completion.enable = '启用自动完成。'
-config.completion.callSnippet = '显示函数调用片段。'
-config.completion.callSnippet.Disable = "只显示 `函数名`。"
-config.completion.callSnippet.Both = "显示 `函数名` 与 `调用片段`。"
-config.completion.callSnippet.Replace = "只显示 `调用片段`。"
-config.completion.keywordSnippet = '显示关键字语法片段'
-config.completion.keywordSnippet.Disable = "只显示 `关键字`。"
-config.completion.keywordSnippet.Both = "显示 `关键字` 与 `语法片段`。"
-config.completion.keywordSnippet.Replace = "只显示 `语法片段`。"
-config.completion.displayContext = "预览建议的相关代码片段,可能可以帮助你了解这项建议的用法。设置的数字表示代码片段的截取行数,设置为`0`可以禁用此功能。"
-config.completion.workspaceWord = "显示的上下文单词是否包含工作区中其他文件的内容。"
-config.completion.showWord = "在建议中显示上下文单词。"
-config.completion.showWord.Enable = "总是在建议中显示上下文单词。"
-config.completion.showWord.Fallback = "无法根据语义提供建议时才显示上下文单词。"
-config.completion.showWord.Disable = "不显示上下文单词。"
-config.completion.autoRequire = "输入内容看起来是个文件名时,自动 `require` 此文件。"
-config.completion.showParams = "在建议列表中显示函数的参数信息,函数拥有多个定义时会分开显示。"
-config.completion.requireSeparator = "`require` 时使用的分隔符。"
-config.completion.postfix = "用于触发后缀建议的符号。"
-config.color.mode = "着色模式。"
-config.color.mode.Semantic = "语义着色。你可能需要同时将 `editor.semanticHighlighting.enabled` 设置为 `true` 才能生效。"
-config.color.mode.SemanticEnhanced = "增强的语义颜色。 类似于`Semantic`,但会进行额外的分析(也会带来额外的开销)。"
-config.color.mode.Grammar = "语法着色。"
-config.semantic.enable = "启用语义着色。你可能需要同时将 `editor.semanticHighlighting.enabled` 设置为 `true` 才能生效。"
-config.semantic.variable = "对变量/字段/参数进行语义着色。"
-config.semantic.annotation = "对类型注解进行语义着色。"
-config.semantic.keyword = "对关键字/字面量/运算符进行语义着色。只有当你的编辑器无法进行语法着色时才需要启用此功能。"
-config.signatureHelp.enable = "启用参数提示。"
-config.hover.enable = "启用悬停提示。"
-config.hover.viewString = "悬停提示查看字符串内容(仅当字面量包含转义符时)。"
-config.hover.viewStringMax = "悬停提示查看字符串内容时的最大长度。"
-config.hover.viewNumber = "悬停提示查看数字内容(仅当字面量不是十进制时)。"
-config.hover.fieldInfer = "悬停提示查看表时,会对表的每个字段进行类型推测,当类型推测的用时累计达到该设定值(毫秒)时,将跳过后续字段的类型推测。"
-config.hover.previewFields = "悬停提示查看表时,限制表内字段的最大预览数量。"
-config.hover.enumsLimit = "当值对应多个类型时,限制类型的显示数量。"
-config.develop.enable = '开发者模式。请勿开启,会影响性能。'
-config.develop.debuggerPort = '调试器监听端口。'
-config.develop.debuggerWait = '调试器连接之前挂起。'
-config.intelliSense.searchDepth = '设置智能感知的搜索深度。增大该值可以增加准确度,但会降低性能。不同的项目对该设置的容忍度差异较大,请自己调整为合适的值。'
-config.intelliSense.fastGlobal = '在对全局变量进行补全,及查看 `_G` 的悬浮提示时进行优化。这会略微降低类型推测的准确度,但是对于大量使用全局变量的项目会有大幅的性能提升。'
-config.window.statusBar = '在状态栏显示插件状态。'
-config.window.progressBar = '在状态栏显示进度条。'
-config.hint.enable = '启用内联提示。'
-config.hint.paramType = '在函数的参数位置提示类型。'
-config.hint.setType = '在赋值操作位置提示类型。'
-config.hint.paramName = '在函数调用处提示参数名。'
-config.hint.paramName.All = '所有类型的参数均进行提示。'
-config.hint.paramName.Literal = '只有字面量类型的参数进行提示。'
-config.hint.paramName.Disable = '禁用参数提示。'
-config.hint.arrayIndex = '在构造表时提示数组索引。'
-config.hint.arrayIndex.Enable = '所有的表中都提示数组索引。'
-config.hint.arrayIndex.Auto = '只有表大于3项,或者表是混合类型时才进行提示。'
-config.hint.arrayIndex.Disable = '禁用数组索引提示。'
-config.telemetry.enable = [[
+config.workspace.userThirdParty =
+'在这里添加私有的第三方库适配文件路径,请参考内置的[配置文件路径](https://github.com/sumneko/lua-language-server/tree/master/meta/3rd)'
+config.completion.enable =
+'启用自动完成。'
+config.completion.callSnippet =
+'显示函数调用片段。'
+config.completion.callSnippet.Disable =
+"只显示 `函数名`。"
+config.completion.callSnippet.Both =
+"显示 `函数名` 与 `调用片段`。"
+config.completion.callSnippet.Replace =
+"只显示 `调用片段`。"
+config.completion.keywordSnippet =
+'显示关键字语法片段'
+config.completion.keywordSnippet.Disable =
+"只显示 `关键字`。"
+config.completion.keywordSnippet.Both =
+"显示 `关键字` 与 `语法片段`。"
+config.completion.keywordSnippet.Replace =
+"只显示 `语法片段`。"
+config.completion.displayContext =
+"预览建议的相关代码片段,可能可以帮助你了解这项建议的用法。设置的数字表示代码片段的截取行数,设置为`0`可以禁用此功能。"
+config.completion.workspaceWord =
+"显示的上下文单词是否包含工作区中其他文件的内容。"
+config.completion.showWord =
+"在建议中显示上下文单词。"
+config.completion.showWord.Enable =
+"总是在建议中显示上下文单词。"
+config.completion.showWord.Fallback =
+"无法根据语义提供建议时才显示上下文单词。"
+config.completion.showWord.Disable =
+"不显示上下文单词。"
+config.completion.autoRequire =
+"输入内容看起来是个文件名时,自动 `require` 此文件。"
+config.completion.showParams =
+"在建议列表中显示函数的参数信息,函数拥有多个定义时会分开显示。"
+config.completion.requireSeparator =
+"`require` 时使用的分隔符。"
+config.completion.postfix =
+"用于触发后缀建议的符号。"
+config.color.mode =
+"着色模式。"
+config.color.mode.Semantic =
+"语义着色。你可能需要同时将 `editor.semanticHighlighting.enabled` 设置为 `true` 才能生效。"
+config.color.mode.SemanticEnhanced =
+"增强的语义颜色。 类似于`Semantic`,但会进行额外的分析(也会带来额外的开销)。"
+config.color.mode.Grammar =
+"语法着色。"
+config.semantic.enable =
+"启用语义着色。你可能需要同时将 `editor.semanticHighlighting.enabled` 设置为 `true` 才能生效。"
+config.semantic.variable =
+"对变量/字段/参数进行语义着色。"
+config.semantic.annotation =
+"对类型注解进行语义着色。"
+config.semantic.keyword =
+"对关键字/字面量/运算符进行语义着色。只有当你的编辑器无法进行语法着色时才需要启用此功能。"
+config.signatureHelp.enable =
+"启用参数提示。"
+config.hover.enable =
+"启用悬停提示。"
+config.hover.viewString =
+"悬停提示查看字符串内容(仅当字面量包含转义符时)。"
+config.hover.viewStringMax =
+"悬停提示查看字符串内容时的最大长度。"
+config.hover.viewNumber =
+"悬停提示查看数字内容(仅当字面量不是十进制时)。"
+config.hover.fieldInfer =
+"悬停提示查看表时,会对表的每个字段进行类型推测,当类型推测的用时累计达到该设定值(毫秒)时,将跳过后续字段的类型推测。"
+config.hover.previewFields =
+"悬停提示查看表时,限制表内字段的最大预览数量。"
+config.hover.enumsLimit =
+"当值对应多个类型时,限制类型的显示数量。"
+config.develop.enable =
+'开发者模式。请勿开启,会影响性能。'
+config.develop.debuggerPort =
+'调试器监听端口。'
+config.develop.debuggerWait =
+'调试器连接之前挂起。'
+config.intelliSense.searchDepth =
+'设置智能感知的搜索深度。增大该值可以增加准确度,但会降低性能。不同的项目对该设置的容忍度差异较大,请自己调整为合适的值。'
+config.intelliSense.fastGlobal =
+'在对全局变量进行补全,及查看 `_G` 的悬浮提示时进行优化。这会略微降低类型推测的准确度,但是对于大量使用全局变量的项目会有大幅的性能提升。'
+config.window.statusBar =
+'在状态栏显示插件状态。'
+config.window.progressBar =
+'在状态栏显示进度条。'
+config.hint.enable =
+'启用内联提示。'
+config.hint.paramType =
+'在函数的参数位置提示类型。'
+config.hint.setType =
+'在赋值操作位置提示类型。'
+config.hint.paramName =
+'在函数调用处提示参数名。'
+config.hint.paramName.All =
+'所有类型的参数均进行提示。'
+config.hint.paramName.Literal =
+'只有字面量类型的参数进行提示。'
+config.hint.paramName.Disable =
+'禁用参数提示。'
+config.hint.arrayIndex =
+'在构造表时提示数组索引。'
+config.hint.arrayIndex.Enable =
+'所有的表中都提示数组索引。'
+config.hint.arrayIndex.Auto =
+'只有表大于3项,或者表是混合类型时才进行提示。'
+config.hint.arrayIndex.Disable =
+'禁用数组索引提示。'
+config.format.enable =
+'启用代码格式化程序。'
+config.telemetry.enable =
+[[
启用遥测,通过网络发送你的编辑器信息与错误日志。在[此处](https://github.com/sumneko/lua-language-server/wiki/%E9%9A%90%E7%A7%81%E5%A3%B0%E6%98%8E)阅读我们的隐私声明。
]]
-config.misc.parameters = 'VSCode中启动语言服务时的[命令行参数](https://github.com/sumneko/lua-language-server/wiki/Command-line)。'
-config.IntelliSense.traceLocalSet = '请查阅[文档](https://github.com/sumneko/lua-language-server/wiki/IntelliSense-optional-features)了解用法。'
-config.IntelliSense.traceReturn = '请查阅[文档](https://github.com/sumneko/lua-language-server/wiki/IntelliSense-optional-features)了解用法。'
-config.IntelliSense.traceBeSetted = '请查阅[文档](https://github.com/sumneko/lua-language-server/wiki/IntelliSense-optional-features)了解用法。'
-config.IntelliSense.traceFieldInject = '请查阅[文档](https://github.com/sumneko/lua-language-server/wiki/IntelliSense-optional-features)了解用法。'
+config.misc.parameters =
+'VSCode中启动语言服务时的[命令行参数](https://github.com/sumneko/lua-language-server/wiki/Command-line)。'
+config.IntelliSense.traceLocalSet =
+'请查阅[文档](https://github.com/sumneko/lua-language-server/wiki/IntelliSense-optional-features)了解用法。'
+config.IntelliSense.traceReturn =
+'请查阅[文档](https://github.com/sumneko/lua-language-server/wiki/IntelliSense-optional-features)了解用法。'
+config.IntelliSense.traceBeSetted =
+'请查阅[文档](https://github.com/sumneko/lua-language-server/wiki/IntelliSense-optional-features)了解用法。'
+config.IntelliSense.traceFieldInject =
+'请查阅[文档](https://github.com/sumneko/lua-language-server/wiki/IntelliSense-optional-features)了解用法。'
-config.diagnostics['unused-local'] = '未使用的局部变量'
-config.diagnostics['unused-function'] = '未使用的函数'
-config.diagnostics['undefined-global'] = '未定义的全局变量'
-config.diagnostics['global-in-nil-env'] = '不能使用全局变量( `_ENV` 被设置为了 `nil`)'
-config.diagnostics['unused-label'] = '未使用的标签'
-config.diagnostics['unused-vararg'] = '未使用的不定参数'
-config.diagnostics['trailing-space'] = '后置空格'
-config.diagnostics['redefined-local'] = '重复定义的局部变量'
-config.diagnostics['newline-call'] = '以 `(` 开始的新行,在语法上被解析为了上一行的函数调用'
-config.diagnostics['newfield-call'] = '在字面量表中,2行代码之间缺少分隔符,在语法上被解析为了一次索引操作'
-config.diagnostics['redundant-parameter'] = '函数调用时,传入了多余的参数'
-config.diagnostics['ambiguity-1'] = '优先级歧义,如:`num or 0 + 1`,推测用户的实际期望为 `(num or 0) + 1` '
-config.diagnostics['lowercase-global'] = '首字母小写的全局变量定义'
-config.diagnostics['undefined-env-child'] = '`_ENV` 被设置为了新的字面量表,但是试图获取的全局变量不再这张表中'
-config.diagnostics['duplicate-index'] = '在字面量表中重复定义了索引'
-config.diagnostics['empty-block'] = '空代码块'
-config.diagnostics['redundant-value'] = '赋值操作时,值的数量比被赋值的对象多'
+config.diagnostics['unused-local'] =
+'未使用的局部变量'
+config.diagnostics['unused-function'] =
+'未使用的函数'
+config.diagnostics['undefined-global'] =
+'未定义的全局变量'
+config.diagnostics['global-in-nil-env'] =
+'不能使用全局变量( `_ENV` 被设置为了 `nil`)'
+config.diagnostics['unused-label'] =
+'未使用的标签'
+config.diagnostics['unused-vararg'] =
+'未使用的不定参数'
+config.diagnostics['trailing-space'] =
+'后置空格'
+config.diagnostics['redefined-local'] =
+'重复定义的局部变量'
+config.diagnostics['newline-call'] =
+'以 `(` 开始的新行,在语法上被解析为了上一行的函数调用'
+config.diagnostics['newfield-call'] =
+'在字面量表中,2行代码之间缺少分隔符,在语法上被解析为了一次索引操作'
+config.diagnostics['redundant-parameter'] =
+'函数调用时,传入了多余的参数'
+config.diagnostics['ambiguity-1'] =
+'优先级歧义,如:`num or 0 + 1`,推测用户的实际期望为 `(num or 0) + 1` '
+config.diagnostics['lowercase-global'] =
+'首字母小写的全局变量定义'
+config.diagnostics['undefined-env-child'] =
+'`_ENV` 被设置为了新的字面量表,但是试图获取的全局变量不再这张表中'
+config.diagnostics['duplicate-index'] =
+'在字面量表中重复定义了索引'
+config.diagnostics['empty-block'] =
+'空代码块'
+config.diagnostics['redundant-value'] =
+'赋值操作时,值的数量比被赋值的对象多'
diff --git a/meta/3rd/love2d/library/love.graphics.lua b/meta/3rd/love2d/library/love.graphics.lua
index d2f8c7d8..056cfef1 100644
--- a/meta/3rd/love2d/library/love.graphics.lua
+++ b/meta/3rd/love2d/library/love.graphics.lua
@@ -92,7 +92,9 @@ function love.graphics.discard(discardcolor, discardstencil) end
---
---The right and bottom edges of the object are shifted at an angle defined by the shearing factors.
---
----When using the default shader anything drawn with this function will be tinted according to the currently selected color. Set it to pure white to preserve the object's original colors.
+---When using the default shader anything drawn with this function will be tinted according to the currently selected color.
+---
+---Set it to pure white to preserve the object's original colors.
---
---@overload fun(texture: love.Texture, quad: love.Quad, x: number, y: number, r: number, sx: number, sy: number, ox: number, oy: number, kx: number, ky: number)
---@overload fun(drawable: love.Drawable, transform: love.Transform)
@@ -418,7 +420,9 @@ function love.graphics.getTextureTypes() end
function love.graphics.getWidth() end
---
----Sets the scissor to the rectangle created by the intersection of the specified rectangle with the existing scissor. If no scissor is active yet, it behaves like love.graphics.setScissor.
+---Sets the scissor to the rectangle created by the intersection of the specified rectangle with the existing scissor.
+---
+---If no scissor is active yet, it behaves like love.graphics.setScissor.
---
---The scissor limits the drawing area to a specified rectangle. This affects all graphics calls, including love.graphics.clear.
---
@@ -718,7 +722,9 @@ function love.graphics.present() end
---
---Draws text on screen. If no Font is set, one will be created and set (once) if needed.
---
----As of LOVE 0.7.1, when using translation and scaling functions while drawing text, this function assumes the scale occurs first. If you don't script with this in mind, the text won't be in the right position, or possibly even on screen.
+---As of LOVE 0.7.1, when using translation and scaling functions while drawing text, this function assumes the scale occurs first.
+---
+---If you don't script with this in mind, the text won't be in the right position, or possibly even on screen.
---
---love.graphics.print and love.graphics.printf both support UTF-8 encoding. You'll also need a proper Font for special characters.
---
diff --git a/meta/3rd/love2d/library/love.lua b/meta/3rd/love2d/library/love.lua
index c1c55c69..8c2e3f18 100644
--- a/meta/3rd/love2d/library/love.lua
+++ b/meta/3rd/love2d/library/love.lua
@@ -1,6 +1,7 @@
---@meta
-- version: 11.4
+
---@class love
love = {}
diff --git a/meta/3rd/lovr/library/callback.lua b/meta/3rd/lovr/library/callback.lua
index 3fb0a960..13cbef51 100644
--- a/meta/3rd/lovr/library/callback.lua
+++ b/meta/3rd/lovr/library/callback.lua
@@ -1,19 +1,47 @@
---@meta
---
----The `lovr.conf` callback lets you configure default settings for LÖVR. It is called once right before the game starts. Make sure you put `lovr.conf` in a file called `conf.lua`, a special file that's loaded before the rest of the framework initializes.
+---The `lovr.conf` callback lets you configure default settings for LÖVR.
+---
+---It is called once right before the game starts.
+---
+---Make sure you put `lovr.conf` in a file called `conf.lua`, a special file that's loaded before the rest of the framework initializes.
+---
+---
+---### NOTE:
+---Disabling the headset module can improve startup time a lot if you aren't intending to use `lovr.headset`.
+---
+---You can set `t.window` to nil to avoid creating the window. You can do it yourself later by using `lovr.graphics.createWindow`.
+---
+---If the `lovr.graphics` module is disabled or the window isn't created, attempting to use any functionality requiring graphics may cause a crash.
+---
+---Enabling the `t.graphics.debug` flag will add additional error checks and will send messages from the GPU driver to the `lovr.log` callback.
+---
+---This will decrease performance but can help provide information on performance problems or other bugs.
+---
+---The `headset.offset` field is a vertical offset applied to the scene for headsets that do not center their tracking origin on the floor.
+---
+---This can be thought of as a "default user height". Setting this offset makes it easier to design experiences that work in both seated and standing VR configurations.
---
---@type fun(t: table)
lovr.conf = nil
---
----This callback is called every frame. Use it to render the scene. If a VR headset is connected, anything rendered by this function will appear in the headset display. The display is cleared to the background color before this function is called.
+---This callback is called every frame.
+---
+---Use it to render the scene.
+---
+---If a VR headset is connected, anything rendered by this function will appear in the headset display.
+---
+---The display is cleared to the background color before this function is called.
---
---@type fun()
lovr.draw = nil
---
----The "lovr.errhand" callback is run whenever an error occurs. It receives two parameters. The first is a string containing the error message. The second is either nil, or a string containing a traceback (as returned by "debug.traceback()"); if nil, this means "lovr.errhand" is being called in the stack where the error occurred, and it can call "debug.traceback()" itself.
+---The "lovr.errhand" callback is run whenever an error occurs.
+---
+---It receives two parameters. The first is a string containing the error message. The second is either nil, or a string containing a traceback (as returned by "debug.traceback()"); if nil, this means "lovr.errhand" is being called in the stack where the error occurred, and it can call "debug.traceback()" itself.
---
---"lovr.errhand" should return a handler function to run in a loop to show the error screen. This handler function is of the same type as the one returned by "lovr.run" and has the same requirements (such as pumping events). If an error occurs while this handler is running, the program will terminate immediately-- "lovr.errhand" will not be given a second chance. Errors which occur inside "lovr.errhand" or in the handler it returns may not be cleanly reported, so be careful.
---
@@ -23,7 +51,11 @@ lovr.draw = nil
lovr.errhand = nil
---
----The `lovr.focus` callback is called whenever the application acquires or loses focus (for example, when opening or closing the Steam dashboard). The callback receives a single argument, focused, which is a boolean indicating whether or not the application is now focused. It may make sense to pause the game or reduce visual fidelity when the application loses focus.
+---The `lovr.focus` callback is called whenever the application acquires or loses focus (for example, when opening or closing the Steam dashboard).
+---
+---The callback receives a single argument, focused, which is a boolean indicating whether or not the application is now focused.
+---
+---It may make sense to pause the game or reduce visual fidelity when the application loses focus.
---
---@type fun(focused: boolean)
lovr.focus = nil
@@ -41,35 +73,67 @@ lovr.keypressed = nil
lovr.keyreleased = nil
---
----This callback is called once when the app starts. It should be used to perform initial setup work, like loading resources and initializing classes and variables.
+---This callback is called once when the app starts.
+---
+---It should be used to perform initial setup work, like loading resources and initializing classes and variables.
+---
+---
+---### NOTE:
+---If the project was loaded from a restart using `lovr.event.restart`, the return value from the previously-run `lovr.restart` callback will be made available to this callback as the `restart` key in the `args` table.
+---
+---The `args` table follows the [Lua standard](https://en.wikibooks.org/wiki/Lua_Programming/command_line_parameter).
+---
+---The arguments passed in from the shell are put into a global table named `arg` and passed to `lovr.load`, but with indices offset such that the "script" (the project path) is at index 0.
+---
+---So all arguments (if any) intended for the project are at successive indices starting with 1, and the executable and its "internal" arguments are in normal order but stored in negative indices.
---
---@type fun(args: table)
lovr.load = nil
---
----This callback is called when a message is logged. The default implementation of this callback prints the message to the console using `print`, but it's possible to override this callback to render messages in VR, write them to a file, filter messages, and more.
+---This callback is called when a message is logged.
+---
+---The default implementation of this callback prints the message to the console using `print`, but it's possible to override this callback to render messages in VR, write them to a file, filter messages, and more.
---
---The message can have a "tag" that is a short string representing the sender, and a "level" indicating how severe the message is.
---
----The `t.graphics.debug` flag in `lovr.conf` can be used to get log messages from the GPU driver (tagged as `GL`). It is also possible to emit your own log messages using `lovr.event.push`.
+---The `t.graphics.debug` flag in `lovr.conf` can be used to get log messages from the GPU driver (tagged as `GL`).
+---
+---It is also possible to emit your own log messages using `lovr.event.push`.
---
---@type fun(message: string, level: string, tag: string)
lovr.log = nil
---
----This callback is called every frame after rendering to the headset and is usually used to render a mirror of the headset display onto the desktop window. It can be overridden for custom mirroring behavior. For example, you could render a single eye instead of a stereo view, apply postprocessing effects, add 2D UI, or render the scene from an entirely different viewpoint for a third person camera.
+---This callback is called every frame after rendering to the headset and is usually used to render a mirror of the headset display onto the desktop window.
+---
+---It can be overridden for custom mirroring behavior.
+---
+---For example, you could render a single eye instead of a stereo view, apply postprocessing effects, add 2D UI, or render the scene from an entirely different viewpoint for a third person camera.
+---
+---
+---### NOTE:
+---When this callback is called, the camera is located at `(0, 0, 0)` and is looking down the negative-z axis.
+---
+---Note that the usual graphics state applies while `lovr.mirror` is invoked, so you may need to reset graphics state at the end of `lovr.draw` to get the result you want.
---
---@type fun()
lovr.mirror = nil
---
----This callback contains a permission response previously requested with `lovr.system.requestPermission`. The callback contains information on whether permission was granted or denied.
+---This callback contains a permission response previously requested with `lovr.system.requestPermission`.
+---
+---The callback contains information on whether permission was granted or denied.
---
---@type fun(permission: lovr.Permission, granted: boolean)
lovr.permission = nil
---
----This callback is called right before the application is about to quit. Use it to perform any necessary cleanup work. A truthy value can be returned from this callback to abort quitting.
+---This callback is called right before the application is about to quit.
+---
+---Use it to perform any necessary cleanup work.
+---
+---A truthy value can be returned from this callback to abort quitting.
---
---@type fun():boolean
lovr.quit = nil
@@ -81,13 +145,23 @@ lovr.quit = nil
lovr.resize = nil
---
----This callback is called when a restart from `lovr.event.restart` is happening. A value can be returned to send it to the next LÖVR instance, available as the `restart` key in the argument table passed to `lovr.load`. Object instances can not be used as the restart value, since they are destroyed as part of the cleanup process.
+---This callback is called when a restart from `lovr.event.restart` is happening.
+---
+---A value can be returned to send it to the next LÖVR instance, available as the `restart` key in the argument table passed to `lovr.load`.
+---
+---Object instances can not be used as the restart value, since they are destroyed as part of the cleanup process.
+---
+---
+---### NOTE:
+---Only nil, booleans, numbers, and strings are supported types for the return value.
---
---@type fun():any
lovr.restart = nil
---
----This callback is the main entry point for a LÖVR program. It is responsible for calling `lovr.load` and returning the main loop function.
+---This callback is the main entry point for a LÖVR program.
+---
+---It is responsible for calling `lovr.load` and returning the main loop function.
---
---@type fun():function
lovr.run = nil
@@ -97,11 +171,21 @@ lovr.run = nil
---
---For example, when `shift + 1` is pressed on an American keyboard, `lovr.textinput` will be called with `!`.
---
+---
+---### NOTE:
+---Some characters in UTF-8 unicode take multiple bytes to encode.
+---
+---Due to the way Lua works, the length of these strings will be bigger than 1 even though they are just a single character. `lovr.graphics.print` is compatible with UTF-8 but doing other string processing on these strings may require a library.
+---
+---Lua 5.3+ has support for working with UTF-8 strings.
+---
---@type fun(text: string, code: number)
lovr.textinput = nil
---
----The `lovr.threaderror` callback is called whenever an error occurs in a Thread. It receives the Thread object where the error occurred and an error message.
+---The `lovr.threaderror` callback is called whenever an error occurs in a Thread.
+---
+---It receives the Thread object where the error occurred and an error message.
---
---The default implementation of this callback will call `lovr.errhand` with the error.
---
@@ -109,7 +193,11 @@ lovr.textinput = nil
lovr.threaderror = nil
---
----The `lovr.update` callback should be used to update your game's logic. It receives a single parameter, `dt`, which represents the amount of elapsed time between frames. You can use this value to scale timers, physics, and animations in your game so they play at a smooth, consistent speed.
+---The `lovr.update` callback should be used to update your game's logic.
+---
+---It receives a single parameter, `dt`, which represents the amount of elapsed time between frames.
+---
+---You can use this value to scale timers, physics, and animations in your game so they play at a smooth, consistent speed.
---
---@type fun(dt: number)
lovr.update = nil
diff --git a/meta/3rd/lovr/library/lovr.audio.lua b/meta/3rd/lovr/library/lovr.audio.lua
index a768b708..71717874 100644
--- a/meta/3rd/lovr/library/lovr.audio.lua
+++ b/meta/3rd/lovr/library/lovr.audio.lua
@@ -1,13 +1,31 @@
---@meta
---
----The `lovr.audio` module is responsible for playing sound effects and music. To play a sound, create a `Source` object and call `Source:play` on it. Currently ogg, wav, and mp3 audio formats are supported.
+---The `lovr.audio` module is responsible for playing sound effects and music.
+---
+---To play a sound, create a `Source` object and call `Source:play` on it.
+---
+---Currently ogg, wav, and mp3 audio formats are supported.
---
---@class lovr.audio
lovr.audio = {}
---
----Returns the global air absorption coefficients for the medium. This affects Sources that have the `absorption` effect enabled, causing audio volume to drop off with distance as it is absorbed by the medium it's traveling through (air, water, etc.). The difference between absorption and falloff is that absorption is more subtle and is frequency-dependent, so higher-frequency bands can get absorbed more quickly than lower ones. This can be used to apply "underwater" effects and stuff.
+---Returns the global air absorption coefficients for the medium.
+---
+---This affects Sources that have the `absorption` effect enabled, causing audio volume to drop off with distance as it is absorbed by the medium it's traveling through (air, water, etc.).
+---
+---The difference between absorption and falloff is that absorption is more subtle and is frequency-dependent, so higher-frequency bands can get absorbed more quickly than lower ones.
+---
+---This can be used to apply "underwater" effects and stuff.
+---
+---
+---### NOTE:
+---Absorption is currently only supported by the phonon spatializer.
+---
+---The frequency bands correspond to `400Hz`, `2.5KHz`, and `15KHz`.
+---
+---The default coefficients are `.0002`, `.0017`, and `.0182` for low, mid, and high.
---
---@return number low # The absorption coefficient for the low frequency band.
---@return number mid # The absorption coefficient for the mid frequency band.
@@ -15,7 +33,9 @@ lovr.audio = {}
function lovr.audio.getAbsorption() end
---
----Returns a list of playback or capture devices. Each device has an `id`, `name`, and a `default` flag indicating whether it's the default device.
+---Returns a list of playback or capture devices.
+---
+---Each device has an `id`, `name`, and a `default` flag indicating whether it's the default device.
---
---To use a specific device id for playback or capture, pass it to `lovr.audio.setDevice`.
---
@@ -55,13 +75,91 @@ function lovr.audio.getPosition() end
---
---Returns the name of the active spatializer (`simple`, `oculus`, or `phonon`).
---
----The `t.audio.spatializer` setting in `lovr.conf` can be used to express a preference for a particular spatializer. If it's `nil`, all spatializers will be tried in the following order: `phonon`, `oculus`, `simple`.
+---The `t.audio.spatializer` setting in `lovr.conf` can be used to express a preference for a particular spatializer.
+---
+---If it's `nil`, all spatializers will be tried in the following order: `phonon`, `oculus`, `simple`.
+---
+---
+---### NOTE:
+---Using a feature or effect that is not supported by the current spatializer will not error, it just won't do anything.
+---
+---<table>
+--- <thead>
+--- <tr>
+--- <td>Feature</td>
+--- <td>simple</td>
+--- <td>phonon</td>
+--- <td>oculus</td>
+--- </tr>
+--- </thead>
+--- <tbody>
+--- <tr>
+--- <td>Effect: Spatialization</td>
+--- <td>x</td>
+--- <td>x</td>
+--- <td>x</td>
+--- </tr>
+--- <tr>
+--- <td>Effect: Attenuation</td>
+--- <td>x</td>
+--- <td>x</td>
+--- <td></td>
+--- </tr>
+--- <tr>
+--- <td>Effect: Absorption</td>
+--- <td></td>
+--- <td>x</td>
+--- <td></td>
+--- </tr>
+--- <tr>
+--- <td>Effect: Occlusion</td>
+--- <td></td>
+--- <td>x</td>
+--- <td></td>
+--- </tr>
+--- <tr>
+--- <td>Effect: Transmission</td>
+--- <td></td>
+--- <td>x</td>
+--- <td></td>
+--- </tr>
+--- <tr>
+--- <td>Effect: Reverb</td>
+--- <td></td>
+--- <td>x</td>
+--- <td></td>
+--- </tr>
+--- <tr>
+--- <td>lovr.audio.setGeometry</td>
+--- <td></td>
+--- <td>x</td>
+--- <td></td>
+--- </tr>
+--- <tr>
+--- <td>Source:setDirectivity</td>
+--- <td>x</td>
+--- <td>x</td>
+--- <td></td>
+--- </tr>
+--- <tr>
+--- <td>Source:setRadius</td>
+--- <td></td>
+--- <td>x</td>
+--- <td></td>
+--- </tr>
+--- </tbody> </table>
---
---@return string spatializer # The name of the active spatializer.
function lovr.audio.getSpatializer() end
---
----Returns the master volume. All audio sent to the playback device has its volume multiplied by this factor.
+---Returns the master volume.
+---
+---All audio sent to the playback device has its volume multiplied by this factor.
+---
+---
+---### NOTE:
+---The default volume is 1.0 (0 dB).
---
---@param units? lovr.VolumeUnit # The units to return (linear or db).
---@return number volume # The master volume.
@@ -85,7 +183,21 @@ function lovr.audio.isStarted(type) end
function lovr.audio.newSource(filename, options) end
---
----Sets the global air absorption coefficients for the medium. This affects Sources that have the `absorption` effect enabled, causing audio volume to drop off with distance as it is absorbed by the medium it's traveling through (air, water, etc.). The difference between absorption and falloff is that absorption is more subtle and is frequency-dependent, so higher-frequency bands can get absorbed more quickly than lower ones. This can be used to apply "underwater" effects and stuff.
+---Sets the global air absorption coefficients for the medium.
+---
+---This affects Sources that have the `absorption` effect enabled, causing audio volume to drop off with distance as it is absorbed by the medium it's traveling through (air, water, etc.).
+---
+---The difference between absorption and falloff is that absorption is more subtle and is frequency-dependent, so higher-frequency bands can get absorbed more quickly than lower ones.
+---
+---This can be used to apply "underwater" effects and stuff.
+---
+---
+---### NOTE:
+---Absorption is currently only supported by the phonon spatializer.
+---
+---The frequency bands correspond to `400Hz`, `2.5KHz`, and `15KHz`.
+---
+---The default coefficients are `.0002`, `.0017`, and `.0182` for low, mid, and high.
---
---@param low number # The absorption coefficient for the low frequency band.
---@param mid number # The absorption coefficient for the mid frequency band.
@@ -95,13 +207,25 @@ function lovr.audio.setAbsorption(low, mid, high) end
---
---Switches either the playback or capture device to a new one.
---
----If a device for the given type is already active, it will be stopped and destroyed. The new device will not be started automatically, use `lovr.audio.start` to start it.
+---If a device for the given type is already active, it will be stopped and destroyed.
+---
+---The new device will not be started automatically, use `lovr.audio.start` to start it.
---
---A device id (previously retrieved using `lovr.audio.getDevices`) can be given to use a specific audio device, or `nil` can be used for the id to use the default audio device.
---
----A sink can be also be provided when changing the device. A sink is an audio stream (`Sound` object with a `stream` type) that will receive all audio samples played (for playback) or all audio samples captured (for capture). When an audio device with a sink is started, be sure to periodically call `Sound:read` on the sink to read audio samples from it, otherwise it will overflow and discard old data. The sink can have any format, data will be converted as needed. Using a sink for the playback device will reduce performance, but this isn't the case for capture devices.
+---A sink can be also be provided when changing the device.
+---
+---A sink is an audio stream (`Sound` object with a `stream` type) that will receive all audio samples played (for playback) or all audio samples captured (for capture).
---
----Audio devices can be started in `shared` or `exclusive` mode. Exclusive devices may have lower latency than shared devices, but there's a higher chance that requesting exclusive access to an audio device will fail (either because it isn't supported or allowed). One strategy is to first try the device in exclusive mode, switching to shared if it doesn't work.
+---When an audio device with a sink is started, be sure to periodically call `Sound:read` on the sink to read audio samples from it, otherwise it will overflow and discard old data.
+---
+---The sink can have any format, data will be converted as needed. Using a sink for the playback device will reduce performance, but this isn't the case for capture devices.
+---
+---Audio devices can be started in `shared` or `exclusive` mode.
+---
+---Exclusive devices may have lower latency than shared devices, but there's a higher chance that requesting exclusive access to an audio device will fail (either because it isn't supported or allowed).
+---
+---One strategy is to first try the device in exclusive mode, switching to shared if it doesn't work.
---
---@param type? lovr.AudioType # The device to switch.
---@param id? userdata # The id of the device to use, or `nil` to use the default device.
@@ -111,10 +235,26 @@ function lovr.audio.setAbsorption(low, mid, high) end
function lovr.audio.setDevice(type, id, sink, mode) end
---
----Sets a mesh of triangles to use for modeling audio effects, using a table of vertices or a Model. When the appropriate effects are enabled, audio from `Source` objects will correctly be occluded by walls and bounce around to create realistic reverb.
+---Sets a mesh of triangles to use for modeling audio effects, using a table of vertices or a Model.
+---
+---When the appropriate effects are enabled, audio from `Source` objects will correctly be occluded by walls and bounce around to create realistic reverb.
---
---An optional `AudioMaterial` may be provided to specify the acoustic properties of the geometry.
---
+---
+---### NOTE:
+---This is currently only supported/used by the `phonon` spatializer.
+---
+---The `Effect`s that use geometry are:
+---
+---- `occlusion`
+---- `reverb`
+---- `transmission`
+---
+---If an existing geometry has been set, this function will replace it.
+---
+---The triangles must use counterclockwise winding.
+---
---@overload fun(model: lovr.Model, material: lovr.AudioMaterial):boolean
---@param vertices table # A flat table of vertices. Each vertex is 3 numbers representing its x, y, and z position. The units used for audio coordinates are up to you, but meters are recommended.
---@param indices table # A list of indices, indicating how the vertices are connected into triangles. Indices are 1-indexed and are 32 bits (they can be bigger than 65535).
@@ -152,41 +292,80 @@ function lovr.audio.setPose(x, y, z, angle, ax, ay, az) end
function lovr.audio.setPosition(x, y, z) end
---
----Sets the master volume. All audio sent to the playback device has its volume multiplied by this factor.
+---Sets the master volume.
+---
+---All audio sent to the playback device has its volume multiplied by this factor.
+---
+---
+---### NOTE:
+---The volume will be clamped to a 0-1 range (0 dB).
---
---@param volume number # The master volume.
---@param units? lovr.VolumeUnit # The units of the value.
function lovr.audio.setVolume(volume, units) end
---
----Starts the active playback or capture device. By default the playback device is initialized and started, but this can be controlled using the `t.audio.start` flag in `lovr.conf`.
+---Starts the active playback or capture device.
+---
+---By default the playback device is initialized and started, but this can be controlled using the `t.audio.start` flag in `lovr.conf`.
+---
+---
+---### NOTE:
+---Starting an audio device may fail if:
+---
+---- The device is already started
+---- No device was initialized with `lovr.audio.setDevice`
+---- Lack of `audiocapture` permission on Android (see `lovr.system.requestPermission`)
+---- Some other problem accessing the audio device
---
---@param type? lovr.AudioType # The type of device to start.
---@return boolean started # Whether the device was successfully started.
function lovr.audio.start(type) end
---
----Stops the active playback or capture device. This may fail if:
+---Stops the active playback or capture device.
+---
+---This may fail if:
---
---- The device is not started
---- No device was initialized with `lovr.audio.setDevice`
---
+---
+---### NOTE:
+---Switching devices with `lovr.audio.setDevice` will stop the existing one.
+---
---@param type? lovr.AudioType # The type of device to stop.
---@return boolean stopped # Whether the device was successfully stopped.
function lovr.audio.stop(type) end
---
----A Source is an object representing a single sound. Currently ogg, wav, and mp3 formats are supported.
+---A Source is an object representing a single sound.
+---
+---Currently ogg, wav, and mp3 formats are supported.
+---
+---When a Source is playing, it will send audio to the speakers.
+---
+---Sources do not play automatically when they are created.
---
----When a Source is playing, it will send audio to the speakers. Sources do not play automatically when they are created. Instead, the `play`, `pause`, and `stop` functions can be used to control when they should play.
+---Instead, the `play`, `pause`, and `stop` functions can be used to control when they should play.
---
----`Source:seek` and `Source:tell` can be used to control the playback position of the Source. A Source can be set to loop when it reaches the end using `Source:setLooping`.
+---`Source:seek` and `Source:tell` can be used to control the playback position of the Source.
+---
+---A Source can be set to loop when it reaches the end using `Source:setLooping`.
---
---@class lovr.Source
local Source = {}
---
----Creates a copy of the Source, referencing the same `Sound` object and inheriting all of the settings of this Source. However, it will be created in the stopped state and will be rewound to the beginning.
+---Creates a copy of the Source, referencing the same `Sound` object and inheriting all of the settings of this Source.
+---
+---However, it will be created in the stopped state and will be rewound to the beginning.
+---
+---
+---### NOTE:
+---This is a good way to create multiple Sources that play the same sound, since the audio data won't be loaded multiple times and can just be reused.
+---
+---You can also create multiple `Source` objects and pass in the same `Sound` object for each one, which will have the same effect.
---
---@return lovr.Source source # A genetically identical copy of the Source.
function Source:clone() end
@@ -196,9 +375,21 @@ function Source:clone() end
---
---The directivity is controlled by two parameters: the weight and the power.
---
----The weight is a number between 0 and 1 controlling the general "shape" of the sound emitted. 0.0 results in a completely omnidirectional sound that can be heard from all directions. 1.0 results in a full dipole shape that can be heard only from the front and back. 0.5 results in a cardioid shape that can only be heard from one direction. Numbers in between will smoothly transition between these.
+---The weight is a number between 0 and 1 controlling the general "shape" of the sound emitted. 0.0 results in a completely omnidirectional sound that can be heard from all directions.
+---
+---1.0 results in a full dipole shape that can be heard only from the front and back.
+---
+---0.5 results in a cardioid shape that can only be heard from one direction.
+---
+---Numbers in between will smoothly transition between these.
+---
+---The power is a number that controls how "focused" or sharp the shape is.
+---
+---Lower power values can be heard from a wider set of angles.
---
----The power is a number that controls how "focused" or sharp the shape is. Lower power values can be heard from a wider set of angles. It is an exponent, so it can get arbitrarily large. Note that a power of zero will still result in an omnidirectional source, regardless of the weight.
+---It is an exponent, so it can get arbitrarily large.
+---
+---Note that a power of zero will still result in an omnidirectional source, regardless of the weight.
---
---@return number weight # The dipole weight. 0.0 is omnidirectional, 1.0 is a dipole, 0.5 is cardioid.
---@return number power # The dipole power, controlling how focused the directivity shape is.
@@ -233,7 +424,9 @@ function Source:getOrientation() end
function Source:getPose() end
---
----Returns the position of the Source, in meters. Setting the position will cause the Source to be distorted and attenuated based on its position relative to the listener.
+---Returns the position of the Source, in meters.
+---
+---Setting the position will cause the Source to be distorted and attenuated based on its position relative to the listener.
---
---@return number x # The x coordinate.
---@return number y # The y coordinate.
@@ -243,13 +436,23 @@ function Source:getPosition() end
---
---Returns the radius of the Source, in meters.
---
----This does not control falloff or attenuation. It is only used for smoothing out occlusion. If a Source doesn't have a radius, then when it becomes occluded by a wall its volume will instantly drop. Giving the Source a radius that approximates its emitter's size will result in a smooth transition between audible and occluded, improving realism.
+---This does not control falloff or attenuation.
+---
+---It is only used for smoothing out occlusion.
+---
+---If a Source doesn't have a radius, then when it becomes occluded by a wall its volume will instantly drop.
+---
+---Giving the Source a radius that approximates its emitter's size will result in a smooth transition between audible and occluded, improving realism.
---
---@return number radius # The radius of the Source, in meters.
function Source:getRadius() end
---
----Returns the `Sound` object backing the Source. Multiple Sources can share one Sound, allowing its data to only be loaded once. An easy way to do this sharing is by using `Source:clone`.
+---Returns the `Sound` object backing the Source.
+---
+---Multiple Sources can share one Sound, allowing its data to only be loaded once.
+---
+---An easy way to do this sharing is by using `Source:clone`.
---
---@return lovr.Sound sound # The Sound object.
function Source:getSound() end
@@ -264,6 +467,18 @@ function Source:getVolume(units) end
---
---Returns whether a given `Effect` is enabled for the Source.
---
+---
+---### NOTE:
+---The active spatializer will determine which effects are supported.
+---
+---If an unsupported effect is enabled on a Source, no error will be reported.
+---
+---Instead, it will be silently ignored.
+---
+---See `lovr.audio.getSpatializer` for a table showing the effects supported by each spatializer.
+---
+---Calling this function on a Source that was created with `{ effects = false }` will always return false.
+---
---@param effect lovr.Effect # The effect.
---@return boolean enabled # Whether the effect is enabled.
function Source:isEffectEnabled(effect) end
@@ -281,12 +496,22 @@ function Source:isLooping() end
function Source:isPlaying() end
---
----Pauses the source. It can be resumed with `Source:resume` or `Source:play`. If a paused source is rewound, it will remain paused.
+---Pauses the source.
+---
+---It can be resumed with `Source:resume` or `Source:play`. If a paused source is rewound, it will remain paused.
---
function Source:pause() end
---
----Plays the Source. This doesn't do anything if the Source is already playing.
+---Plays the Source.
+---
+---This doesn't do anything if the Source is already playing.
+---
+---
+---### NOTE:
+---There is a maximum of 64 Sources that can be playing at once.
+---
+---If 64 Sources are already playing, this function will return `false`.
---
---@return boolean success # Whether the Source successfully started playing.
function Source:play() end
@@ -294,6 +519,10 @@ function Source:play() end
---
---Seeks the Source to the specified position.
---
+---
+---### NOTE:
+---Seeking a Source backed by a stream `Sound` has no meaningful effect.
+---
---@param position number # The position to seek to.
---@param unit? lovr.TimeUnit # The units for the seek position.
function Source:seek(position, unit) end
@@ -303,9 +532,21 @@ function Source:seek(position, unit) end
---
---The directivity is controlled by two parameters: the weight and the power.
---
----The weight is a number between 0 and 1 controlling the general "shape" of the sound emitted. 0.0 results in a completely omnidirectional sound that can be heard from all directions. 1.0 results in a full dipole shape that can be heard only from the front and back. 0.5 results in a cardioid shape that can only be heard from one direction. Numbers in between will smoothly transition between these.
+---The weight is a number between 0 and 1 controlling the general "shape" of the sound emitted. 0.0 results in a completely omnidirectional sound that can be heard from all directions.
+---
+---1.0 results in a full dipole shape that can be heard only from the front and back.
---
----The power is a number that controls how "focused" or sharp the shape is. Lower power values can be heard from a wider set of angles. It is an exponent, so it can get arbitrarily large. Note that a power of zero will still result in an omnidirectional source, regardless of the weight.
+---0.5 results in a cardioid shape that can only be heard from one direction.
+---
+---Numbers in between will smoothly transition between these.
+---
+---The power is a number that controls how "focused" or sharp the shape is.
+---
+---Lower power values can be heard from a wider set of angles.
+---
+---It is an exponent, so it can get arbitrarily large.
+---
+---Note that a power of zero will still result in an omnidirectional source, regardless of the weight.
---
---@param weight number # The dipole weight. 0.0 is omnidirectional, 1.0 is a dipole, 0.5 is cardioid.
---@param power number # The dipole power, controlling how focused the directivity shape is.
@@ -314,6 +555,18 @@ function Source:setDirectivity(weight, power) end
---
---Enables or disables an effect on the Source.
---
+---
+---### NOTE:
+---The active spatializer will determine which effects are supported.
+---
+---If an unsupported effect is enabled on a Source, no error will be reported.
+---
+---Instead, it will be silently ignored.
+---
+---See `lovr.audio.getSpatializer` for a table showing the effects supported by each spatializer.
+---
+---Calling this function on a Source that was created with `{ effects = false }` will throw an error.
+---
---@param effect lovr.Effect # The effect.
---@param enable boolean # Whether the effect should be enabled.
function Source:setEffectEnabled(effect, enable) end
@@ -321,6 +574,10 @@ function Source:setEffectEnabled(effect, enable) end
---
---Sets whether or not the Source loops.
---
+---
+---### NOTE:
+---Attempting to loop a Source backed by a stream `Sound` will cause an error.
+---
---@param loop boolean # Whether or not the Source will loop.
function Source:setLooping(loop) end
@@ -346,9 +603,13 @@ function Source:setOrientation(angle, ax, ay, az) end
function Source:setPose(x, y, z, angle, ax, ay, az) end
---
----Sets the position of the Source, in meters. Setting the position will cause the Source to be distorted and attenuated based on its position relative to the listener.
+---Sets the position of the Source, in meters.
+---
+---Setting the position will cause the Source to be distorted and attenuated based on its position relative to the listener.
---
----Only mono sources can be positioned. Setting the position of a stereo Source will cause an error.
+---Only mono sources can be positioned.
+---
+---Setting the position of a stereo Source will cause an error.
---
---@param x number # The x coordinate.
---@param y number # The y coordinate.
@@ -358,7 +619,13 @@ function Source:setPosition(x, y, z) end
---
---Sets the radius of the Source, in meters.
---
----This does not control falloff or attenuation. It is only used for smoothing out occlusion. If a Source doesn't have a radius, then when it becomes occluded by a wall its volume will instantly drop. Giving the Source a radius that approximates its emitter's size will result in a smooth transition between audible and occluded, improving realism.
+---This does not control falloff or attenuation.
+---
+---It is only used for smoothing out occlusion.
+---
+---If a Source doesn't have a radius, then when it becomes occluded by a wall its volume will instantly drop.
+---
+---Giving the Source a radius that approximates its emitter's size will result in a smooth transition between audible and occluded, improving realism.
---
---@param radius number # The new radius of the Source, in meters.
function Source:setRadius(radius) end
@@ -366,6 +633,10 @@ function Source:setRadius(radius) end
---
---Sets the current volume factor for the Source.
---
+---
+---### NOTE:
+---The volume will be clamped to a 0-1 range (0 dB).
+---
---@param volume number # The new volume.
---@param units? lovr.VolumeUnit # The units of the value.
function Source:setVolume(volume, units) end
@@ -378,6 +649,10 @@ function Source:stop() end
---
---Returns the current playback position of the Source.
---
+---
+---### NOTE:
+---The return value for Sources backed by a stream `Sound` has no meaning.
+---
---@param unit? lovr.TimeUnit # The unit to return.
---@return number position # The current playback position.
function Source:tell(unit) end
@@ -406,15 +681,23 @@ function Source:tell(unit) end
---Concrete.
---
---| '"concrete"'
+
---| '"glass"'
+
---| '"gravel"'
+
---| '"metal"'
+
---| '"plaster"'
+
---| '"rock"'
+
---| '"wood"'
---
----Audio devices can be created in shared mode or exclusive mode. In exclusive mode, the audio device is the only one active on the system, which gives better performance and lower latency. However, exclusive devices aren't always supported and might not be allowed, so there is a higher chance that creating one will fail.
+---Audio devices can be created in shared mode or exclusive mode.
+---
+---In exclusive mode, the audio device is the only one active on the system, which gives better performance and lower latency. However, exclusive devices aren't always supported and might not be allowed, so there is a higher chance that creating one will fail.
---
---@alias lovr.AudioShareMode
---
@@ -442,6 +725,16 @@ function Source:tell(unit) end
---
---Different types of effects that can be applied with `Source:setEffectEnabled`.
---
+---
+---### NOTE:
+---The active spatializer will determine which effects are supported.
+---
+---If an unsupported effect is enabled on a Source, no error will be reported.
+---
+---Instead, it will be silently ignored.
+---
+---TODO: expose a table of supported effects for spatializers in docs or from Lua.
+---
---@alias lovr.Effect
---
---Models absorption as sound travels through the air, water, etc.
@@ -469,7 +762,9 @@ function Source:tell(unit) end
---| '"transmission"'
---
----When figuring out how long a Source is or seeking to a specific position in the sound file, units can be expressed in terms of seconds or in terms of frames. A frame is one set of samples for each channel (one sample for mono, two samples for stereo).
+---When figuring out how long a Source is or seeking to a specific position in the sound file, units can be expressed in terms of seconds or in terms of frames.
+---
+---A frame is one set of samples for each channel (one sample for mono, two samples for stereo).
---
---@alias lovr.TimeUnit
---
diff --git a/meta/3rd/lovr/library/lovr.data.lua b/meta/3rd/lovr/library/lovr.data.lua
index 9c34b189..a699a2f3 100644
--- a/meta/3rd/lovr/library/lovr.data.lua
+++ b/meta/3rd/lovr/library/lovr.data.lua
@@ -17,7 +17,17 @@ lovr.data = {}
function lovr.data.newBlob(size, name) end
---
----Creates a new Image. Image data can be loaded and decoded from an image file, or a raw block of pixels with a specified width, height, and format can be created.
+---Creates a new Image.
+---
+---Image data can be loaded and decoded from an image file, or a raw block of pixels with a specified width, height, and format can be created.
+---
+---
+---### NOTE:
+---The supported image file formats are png, jpg, hdr, dds (DXT1, DXT3, DXT5), ktx, and astc.
+---
+---Only 2D textures are supported for DXT/ASTC.
+---
+---Currently textures loaded as KTX need to be in DXT/ASTC formats.
---
---@overload fun(width: number, height: number, format: lovr.TextureFormat, data: lovr.Blob):lovr.Image
---@overload fun(source: lovr.Image):lovr.Image
@@ -28,7 +38,9 @@ function lovr.data.newBlob(size, name) end
function lovr.data.newImage(filename, flip) end
---
----Loads a 3D model from a file. The supported 3D file formats are OBJ and glTF.
+---Loads a 3D model from a file.
+---
+---The supported 3D file formats are OBJ and glTF.
---
---@overload fun(blob: lovr.Blob):lovr.ModelData
---@param filename string # The filename of the model to load.
@@ -45,11 +57,43 @@ function lovr.data.newModelData(filename) end
function lovr.data.newRasterizer(size) end
---
----Creates a new Sound. A sound can be loaded from an audio file, or it can be created empty with capacity for a certain number of audio frames.
+---Creates a new Sound.
+---
+---A sound can be loaded from an audio file, or it can be created empty with capacity for a certain number of audio frames.
---
---When loading audio from a file, use the `decode` option to control whether compressed audio should remain compressed or immediately get decoded to raw samples.
---
----When creating an empty sound, the `contents` parameter can be set to `'stream'` to create an audio stream. On streams, `Sound:setFrames` will always write to the end of the stream, and `Sound:getFrames` will always read the oldest samples from the beginning. The number of frames in the sound is the total capacity of the stream's buffer.
+---When creating an empty sound, the `contents` parameter can be set to `'stream'` to create an audio stream.
+---
+---On streams, `Sound:setFrames` will always write to the end of the stream, and `Sound:getFrames` will always read the oldest samples from the beginning.
+---
+---The number of frames in the sound is the total capacity of the stream's buffer.
+---
+---
+---### NOTE:
+---It is highly recommended to use an audio format that matches the format of the audio module: `f32` sample formats at a sample rate of 48000, with 1 channel for spatialized sources or 2 channels for unspatialized sources.
+---
+---This will avoid the need to convert audio during playback, which boosts performance of the audio thread.
+---
+---The WAV importer supports 16, 24, and 32 bit integer data and 32 bit floating point data.
+---
+---The data must be mono, stereo, or 4-channel full-sphere ambisonic.
+---
+---The `WAVE_FORMAT_EXTENSIBLE` extension is supported.
+---
+---Ambisonic channel layouts are supported for import (but not yet for playback).
+---
+---Ambisonic data can be loaded from WAV files.
+---
+---It must be first-order full-sphere ambisonic data with 4 channels.
+---
+---If the WAV has a `WAVE_FORMAT_EXTENSIBLE` chunk with an `AMBISONIC_B_FORMAT` format GUID, then the data is understood as using the AMB format with Furse-Malham channel ordering and normalization.
+---
+---*All other* 4-channel files are assumed to be using the AmbiX format with ACN channel ordering and SN3D normalization.
+---
+---AMB files will get automatically converted to AmbiX on import, so ambisonic Sounds will always be in a consistent format.
+---
+---OGG and MP3 files will always have the `f32` format when loaded.
---
---@overload fun(filename: string, decode: boolean):lovr.Sound
---@overload fun(blob: lovr.Blob, decode: boolean):lovr.Sound
@@ -62,7 +106,11 @@ function lovr.data.newRasterizer(size) end
function lovr.data.newSound(frames, format, channels, sampleRate, contents) end
---
----A Blob is an object that holds binary data. It can be passed to most functions that take filename arguments, like `lovr.graphics.newModel` or `lovr.audio.newSource`. Blobs aren't usually necessary for simple projects, but they can be really helpful if:
+---A Blob is an object that holds binary data.
+---
+---It can be passed to most functions that take filename arguments, like `lovr.graphics.newModel` or `lovr.audio.newSource`.
+---
+---Blobs aren't usually necessary for simple projects, but they can be really helpful if:
---
---- You need to work with low level binary data, potentially using the LuaJIT FFI for increased
--- performance.
@@ -76,13 +124,19 @@ function lovr.data.newSound(frames, format, channels, sampleRate, contents) end
local Blob = {}
---
----Returns the filename the Blob was loaded from, or the custom name given to it when it was created. This label is also used in error messages.
+---Returns the filename the Blob was loaded from, or the custom name given to it when it was created.
+---
+---This label is also used in error messages.
---
---@return string name # The name of the Blob.
function Blob:getName() end
---
----Returns a raw pointer to the Blob's data. This can be used to interface with other C libraries using the LuaJIT FFI. Use this only if you know what you're doing!
+---Returns a raw pointer to the Blob's data.
+---
+---This can be used to interface with other C libraries using the LuaJIT FFI.
+---
+---Use this only if you know what you're doing!
---
---@return userdata pointer # A pointer to the data.
function Blob:getPointer() end
@@ -100,7 +154,13 @@ function Blob:getSize() end
function Blob:getString() end
---
----An Image stores raw 2D pixel info for `Texture`s. It has a width, height, and format. The Image can be initialized with the contents of an image file or it can be created with uninitialized contents. The supported image formats are `png`, `jpg`, `hdr`, `dds`, `ktx`, and `astc`.
+---An Image stores raw 2D pixel info for `Texture`s.
+---
+---It has a width, height, and format.
+---
+---The Image can be initialized with the contents of an image file or it can be created with uninitialized contents.
+---
+---The supported image formats are `png`, `jpg`, `hdr`, `dds`, `ktx`, and `astc`.
---
---Usually you can just use Textures, but Image can be useful if you want to manipulate individual pixels, load Textures in a background thread, or use the FFI to efficiently access the raw image data.
---
@@ -108,7 +168,9 @@ function Blob:getString() end
local Image = {}
---
----Encodes the Image to an uncompressed png. This intended mainly for debugging.
+---Encodes the Image to an uncompressed png.
+---
+---This intended mainly for debugging.
---
---@return lovr.Blob blob # A new Blob containing the PNG image data.
function Image:encode() end
@@ -141,6 +203,10 @@ function Image:getHeight() end
---
---Returns the value of a pixel of the Image.
---
+---
+---### NOTE:
+---The following texture formats are supported: `rgba`, `rgb`, `r32f`, `rg32f`, and `rgba32f`.
+---
---@param x number # The x coordinate of the pixel to get (0-indexed).
---@param y number # The y coordinate of the pixel to get (0-indexed).
---@return number r # The red component of the pixel, from 0.0 to 1.0.
@@ -158,6 +224,14 @@ function Image:getWidth() end
---
---Copies a rectangle of pixels from one Image to this one.
---
+---
+---### NOTE:
+---The two Images must have the same pixel format.
+---
+---Compressed images cannot be copied.
+---
+---The rectangle cannot go outside the dimensions of the source or destination textures.
+---
---@param source lovr.Image # The Image to copy pixels from.
---@param x? number # The x coordinate to paste to (0-indexed).
---@param y? number # The y coordinate to paste to (0-indexed).
@@ -170,6 +244,10 @@ function Image:paste(source, x, y, fromX, fromY, width, height) end
---
---Sets the value of a pixel of the Image.
---
+---
+---### NOTE:
+---The following texture formats are supported: `rgba`, `rgb`, `r32f`, `rg32f`, and `rgba32f`.
+---
---@param x number # The x coordinate of the pixel to set (0-indexed).
---@param y number # The y coordinate of the pixel to set (0-indexed).
---@param r number # The red component of the pixel, from 0.0 to 1.0.
@@ -179,7 +257,9 @@ function Image:paste(source, x, y, fromX, fromY, width, height) end
function Image:setPixel(x, y, r, g, b, a) end
---
----A ModelData is a container object that loads and holds data contained in 3D model files. This can include a variety of things like the node structure of the asset, the vertex data it contains, contains, the `Image` and `Material` properties, and any included animations.
+---A ModelData is a container object that loads and holds data contained in 3D model files.
+---
+---This can include a variety of things like the node structure of the asset, the vertex data it contains, contains, the `Image` and `Material` properties, and any included animations.
---
---The current supported formats are OBJ, glTF, and STL.
---
@@ -197,19 +277,27 @@ local ModelData = {}
local Rasterizer = {}
---
----Returns the advance metric of the font, in pixels. The advance is how many pixels the font advances horizontally after each glyph is rendered. This does not include kerning.
+---Returns the advance metric of the font, in pixels.
+---
+---The advance is how many pixels the font advances horizontally after each glyph is rendered.
+---
+---This does not include kerning.
---
---@return number advance # The advance of the font, in pixels.
function Rasterizer:getAdvance() end
---
----Returns the ascent metric of the font, in pixels. The ascent represents how far any glyph of the font ascends above the baseline.
+---Returns the ascent metric of the font, in pixels.
+---
+---The ascent represents how far any glyph of the font ascends above the baseline.
---
---@return number ascent # The ascent of the font, in pixels.
function Rasterizer:getAscent() end
---
----Returns the descent metric of the font, in pixels. The descent represents how far any glyph of the font descends below the baseline.
+---Returns the descent metric of the font, in pixels.
+---
+---The descent represents how far any glyph of the font descends below the baseline.
---
---@return number descent # The descent of the font, in pixels.
function Rasterizer:getDescent() end
@@ -227,7 +315,9 @@ function Rasterizer:getGlyphCount() end
function Rasterizer:getHeight() end
---
----Returns the line height metric of the font, in pixels. This is how far apart lines are.
+---Returns the line height metric of the font, in pixels.
+---
+---This is how far apart lines are.
---
---@return number height # The line height of the font, in pixels.
function Rasterizer:getLineHeight() end
@@ -239,31 +329,75 @@ function Rasterizer:getLineHeight() end
function Rasterizer:hasGlyphs() end
---
----A Sound stores the data for a sound. The supported sound formats are OGG, WAV, and MP3. Sounds cannot be played directly. Instead, there are `Source` objects in `lovr.audio` that are used for audio playback. All Source objects are backed by one of these Sounds, and multiple Sources can share a single Sound to reduce memory usage.
+---A Sound stores the data for a sound.
+---
+---The supported sound formats are OGG, WAV, and MP3.
+---
+---Sounds cannot be played directly.
+---
+---Instead, there are `Source` objects in `lovr.audio` that are used for audio playback.
+---
+---All Source objects are backed by one of these Sounds, and multiple Sources can share a single Sound to reduce memory usage.
---
---Metadata
------
---
----Sounds hold a fixed number of frames. Each frame contains one audio sample for each channel. The `SampleFormat` of the Sound is the data type used for each sample (floating point, integer, etc.). The Sound has a `ChannelLayout`, representing the number of audio channels and how they map to speakers (mono, stereo, etc.). The sample rate of the Sound indicates how many frames should be played per second. The duration of the sound (in seconds) is the number of frames divided by the sample rate.
+---Sounds hold a fixed number of frames.
+---
+---Each frame contains one audio sample for each channel. The `SampleFormat` of the Sound is the data type used for each sample (floating point, integer, etc.).
+---
+---The Sound has a `ChannelLayout`, representing the number of audio channels and how they map to speakers (mono, stereo, etc.).
+---
+---The sample rate of the Sound indicates how many frames should be played per second.
+---
+---The duration of the sound (in seconds) is the number of frames divided by the sample rate.
---
---Compression
------
---
----Sounds can be compressed. Compressed sounds are stored compressed in memory and are decoded as they are played. This uses a lot less memory but increases CPU usage during playback. OGG and MP3 are compressed audio formats. When creating a sound from a compressed format, there is an option to immediately decode it, storing it uncompressed in memory. It can be a good idea to decode short sound effects, since they won't use very much memory even when uncompressed and it will improve CPU usage. Compressed sounds can not be written to using `Sound:setFrames`.
+---Sounds can be compressed.
+---
+---Compressed sounds are stored compressed in memory and are decoded as they are played.
+---
+---This uses a lot less memory but increases CPU usage during playback.
+---
+---OGG and MP3 are compressed audio formats.
+---
+---When creating a sound from a compressed format, there is an option to immediately decode it, storing it uncompressed in memory.
+---
+---It can be a good idea to decode short sound effects, since they won't use very much memory even when uncompressed and it will improve CPU usage.
+---
+---Compressed sounds can not be written to using `Sound:setFrames`.
---
---Streams
------
---
----Sounds can be created as a stream by passing `'stream'` as their contents when creating them. Audio frames can be written to the end of the stream, and read from the beginning. This works well for situations where data is being generated in real time or streamed in from some other data source.
+---Sounds can be created as a stream by passing `'stream'` as their contents when creating them. Audio frames can be written to the end of the stream, and read from the beginning.
+---
+---This works well for situations where data is being generated in real time or streamed in from some other data source.
---
----Sources can be backed by a stream and they'll just play whatever audio is pushed to the stream. The audio module also lets you use a stream as a "sink" for an audio device. For playback devices, this works like loopback, so the mixed audio from all playing Sources will get written to the stream. For capture devices, all the microphone input will get written to the stream. Conversion between sample formats, channel layouts, and sample rates will happen automatically.
+---Sources can be backed by a stream and they'll just play whatever audio is pushed to the stream. The audio module also lets you use a stream as a "sink" for an audio device.
---
----Keep in mind that streams can still only hold a fixed number of frames. If too much data is written before it is read, older frames will start to get overwritten. Similary, it's possible to read too much data without writing fast enough.
+---For playback devices, this works like loopback, so the mixed audio from all playing Sources will get written to the stream.
+---
+---For capture devices, all the microphone input will get written to the stream. Conversion between sample formats, channel layouts, and sample rates will happen automatically.
+---
+---Keep in mind that streams can still only hold a fixed number of frames.
+---
+---If too much data is written before it is read, older frames will start to get overwritten.
+---
+---Similary, it's possible to read too much data without writing fast enough.
---
---Ambisonics
------
---
----Ambisonic sounds can be imported from WAVs, but can not yet be played. Sounds with a `ChannelLayout` of `ambisonic` are stored as first-order full-sphere ambisonics using the AmbiX format (ACN channel ordering and SN3D channel normalization). The AMB format is supported for import and will automatically get converted to AmbiX. See `lovr.data.newSound` for more info.
+---Ambisonic sounds can be imported from WAVs, but can not yet be played.
+---
+---Sounds with a `ChannelLayout` of `ambisonic` are stored as first-order full-sphere ambisonics using the AmbiX format (ACN channel ordering and SN3D channel normalization).
+---
+---The AMB format is supported for import and will automatically get converted to AmbiX.
+---
+---See `lovr.data.newSound` for more info.
---
---@class lovr.Sound
local Sound = {}
@@ -271,11 +405,19 @@ local Sound = {}
---
---Returns a Blob containing the raw bytes of the Sound.
---
+---
+---### NOTE:
+---Samples for each channel are stored interleaved.
+---
+---The data type of each sample is given by `Sound:getFormat`.
+---
---@return lovr.Blob blob # The Blob instance containing the bytes for the `Sound`.
function Sound:getBlob() end
---
----Returns the number of channels in the Sound. Mono sounds have 1 channel, stereo sounds have 2 channels, and ambisonic sounds have 4 channels.
+---Returns the number of channels in the Sound.
+---
+---Mono sounds have 1 channel, stereo sounds have 2 channels, and ambisonic sounds have 4 channels.
---
---@return number channels # The number of channels in the sound.
function Sound:getChannelCount() end
@@ -289,6 +431,10 @@ function Sound:getChannelLayout() end
---
---Returns the duration of the Sound, in seconds.
---
+---
+---### NOTE:
+---This can be computed as `(frameCount / sampleRate)`.
+---
---@return number duration # The duration of the Sound, in seconds.
function Sound:getDuration() end
@@ -299,7 +445,13 @@ function Sound:getDuration() end
function Sound:getFormat() end
---
----Returns the number of frames in the Sound. A frame stores one sample for each channel.
+---Returns the number of frames in the Sound.
+---
+---A frame stores one sample for each channel.
+---
+---
+---### NOTE:
+---For streams, this returns the number of frames in the stream's buffer.
---
---@return number frames # The number of frames in the Sound.
function Sound:getFrameCount() end
@@ -323,17 +475,31 @@ function Sound:getFrames(count, srcOffset) end
---
---Returns the total number of samples in the Sound.
---
+---
+---### NOTE:
+---For streams, this returns the number of samples in the stream's buffer.
+---
---@return number samples # The total number of samples in the Sound.
function Sound:getSampleCount() end
---
----Returns the sample rate of the Sound, in Hz. This is the number of frames that are played every second. It's usually a high number like 48000.
+---Returns the sample rate of the Sound, in Hz.
+---
+---This is the number of frames that are played every second.
+---
+---It's usually a high number like 48000.
---
---@return number frequency # The number of frames per second in the Sound.
function Sound:getSampleRate() end
---
----Returns whether the Sound is compressed. Compressed sounds are loaded from compressed audio formats like MP3 and OGG. They use a lot less memory but require some extra CPU work during playback. Compressed sounds can not be modified using `Sound:setFrames`.
+---Returns whether the Sound is compressed.
+---
+---Compressed sounds are loaded from compressed audio formats like MP3 and OGG.
+---
+---They use a lot less memory but require some extra CPU work during playback.
+---
+---Compressed sounds can not be modified using `Sound:setFrames`.
---
---@return boolean compressed # Whether the Sound is compressed.
function Sound:isCompressed() end
@@ -365,11 +531,17 @@ function Sound:setFrames(t, count, dstOffset, srcOffset) end
---
---| '"mono"'
---
----2 channels. The first channel is for the left speaker and the second is for the right.
+---2 channels.
+---
+---The first channel is for the left speaker and the second is for the right.
---
---| '"stereo"'
---
----4 channels. Ambisonic channels don't map directly to speakers but instead represent directions in 3D space, sort of like the images of a skybox. Currently, ambisonic sounds can only be loaded, not played.
+---4 channels.
+---
+---Ambisonic channels don't map directly to speakers but instead represent directions in 3D space, sort of like the images of a skybox.
+---
+---Currently, ambisonic sounds can only be loaded, not played.
---
---| '"ambisonic"'
diff --git a/meta/3rd/lovr/library/lovr.event.lua b/meta/3rd/lovr/library/lovr.event.lua
index 5beeb5a1..f2e9509d 100644
--- a/meta/3rd/lovr/library/lovr.event.lua
+++ b/meta/3rd/lovr/library/lovr.event.lua
@@ -5,6 +5,12 @@
---
---Due to its low-level nature, it's rare to use `lovr.event` in simple projects.
---
+---
+---### NOTE:
+---You can define your own custom events by adding a function to the `lovr.handlers` table with a key of the name of the event you want to add.
+---
+---Then, push the event using `lovr.event.push`.
+---
---@class lovr.event
lovr.event = {}
@@ -14,24 +20,52 @@ lovr.event = {}
function lovr.event.clear() end
---
----This function returns a Lua iterator for all of the unprocessed items in the event queue. Each event consists of a name as a string, followed by event-specific arguments. This function is called in the default implementation of `lovr.run`, so it is normally not necessary to poll for events yourself.
+---This function returns a Lua iterator for all of the unprocessed items in the event queue.
+---
+---Each event consists of a name as a string, followed by event-specific arguments.
+---
+---This function is called in the default implementation of `lovr.run`, so it is normally not necessary to poll for events yourself.
---
---@return function iterator # The iterator function, usable in a for loop.
function lovr.event.poll() end
---
----Fills the event queue with unprocessed events from the operating system. This function should be called often, otherwise the operating system will consider the application unresponsive. This function is called in the default implementation of `lovr.run`.
+---Fills the event queue with unprocessed events from the operating system.
+---
+---This function should be called often, otherwise the operating system will consider the application unresponsive. This function is called in the default implementation of `lovr.run`.
---
function lovr.event.pump() end
---
----Pushes an event onto the event queue. It will be processed the next time `lovr.event.poll` is called. For an event to be processed properly, there needs to be a function in the `lovr.handlers` table with a key that's the same as the event name.
+---Pushes an event onto the event queue.
+---
+---It will be processed the next time `lovr.event.poll` is called.
+---
+---For an event to be processed properly, there needs to be a function in the `lovr.handlers` table with a key that's the same as the event name.
+---
+---
+---### NOTE:
+---Only nil, booleans, numbers, strings, and LÖVR objects are supported types for event data.
---
---@param name string # The name of the event.
function lovr.event.push(name) end
---
----Pushes an event to quit. An optional number can be passed to set the exit code for the application. An exit code of zero indicates normal termination, whereas a nonzero exit code indicates that an error occurred.
+---Pushes an event to quit.
+---
+---An optional number can be passed to set the exit code for the application.
+---
+---An exit code of zero indicates normal termination, whereas a nonzero exit code indicates that an error occurred.
+---
+---
+---### NOTE:
+---This function is equivalent to calling `lovr.event.push('quit', <args>)`.
+---
+---The event won't be processed until the next time `lovr.event.poll` is called.
+---
+---The `lovr.quit` callback will be called when the event is processed, which can be used to do any cleanup work.
+---
+---The callback can also return `false` to abort the quitting process.
---
---@param code? number # The exit code of the program.
function lovr.event.quit(code) end
@@ -39,10 +73,18 @@ function lovr.event.quit(code) end
---
---Pushes an event to restart the framework.
---
+---
+---### NOTE:
+---The event won't be processed until the next time `lovr.event.poll` is called.
+---
+---The `lovr.restart` callback can be used to persist a value between restarts.
+---
function lovr.event.restart() end
---
----Keys that can be pressed on a keyboard. Notably, numpad keys are missing right now.
+---Keys that can be pressed on a keyboard.
+---
+---Notably, numpad keys are missing right now.
---
---@alias lovr.KeyCode
---
diff --git a/meta/3rd/lovr/library/lovr.filesystem.lua b/meta/3rd/lovr/library/lovr.filesystem.lua
index 37fe8e0e..4f8214db 100644
--- a/meta/3rd/lovr/library/lovr.filesystem.lua
+++ b/meta/3rd/lovr/library/lovr.filesystem.lua
@@ -3,12 +3,40 @@
---
---The `lovr.filesystem` module provides access to the filesystem.
---
+---
+---### NOTE:
+---LÖVR programs can only write to a single directory, called the save directory.
+---
+---The location of the save directory is platform-specific:
+---
+---<table>
+--- <tr>
+--- <td>Windows</td>
+--- <td><code>C:\Users\&lt;user&gt;\AppData\Roaming\LOVR\&lt;identity&gt;</code></td>
+--- </tr>
+--- <tr>
+--- <td>macOS</td>
+--- <td><code>/Users/&lt;user&gt;/Library/Application Support/LOVR/&lt;identity&gt;</code></td>
+--- </tr> </table>
+---
+---`<identity>` should be a unique identifier for your app.
+---
+---It can be set either in `lovr.conf` or by using `lovr.filesystem.setIdentity`.
+---
+---All filenames are relative to either the save directory or the directory containing the project source.
+---
+---Files in the save directory take precedence over files in the project.
+---
---@class lovr.filesystem
lovr.filesystem = {}
---
---Appends content to the end of a file.
---
+---
+---### NOTE:
+---If the file does not exist, it is created.
+---
---@overload fun(filename: string, blob: lovr.Blob):number
---@param filename string # The file to append to.
---@param content string # A string to write to the end of the file.
@@ -16,14 +44,18 @@ lovr.filesystem = {}
function lovr.filesystem.append(filename, content) end
---
----Creates a directory in the save directory. Any parent directories that don't exist will also be created.
+---Creates a directory in the save directory.
+---
+---Any parent directories that don't exist will also be created.
---
---@param path string # The directory to create, recursively.
---@return boolean success # Whether the directory was created.
function lovr.filesystem.createDirectory(path) end
---
----Returns the application data directory. This will be something like:
+---Returns the application data directory.
+---
+---This will be something like:
---
---- `C:\Users\user\AppData\Roaming` on Windows.
---- `/home/user/.config` on Linux.
@@ -35,6 +67,10 @@ function lovr.filesystem.getAppdataDirectory() end
---
---Returns a sorted table containing all files and folders in a single directory.
---
+---
+---### NOTE:
+---This function calls `table.sort` to sort the results, so if `table.sort` is not available in the global scope the results are not guaranteed to be sorted.
+---
---@param path string # The directory.
---@return lovr.items table # A table with a string for each file and subfolder in the directory.
function lovr.filesystem.getDirectoryItems(path) end
@@ -46,7 +82,15 @@ function lovr.filesystem.getDirectoryItems(path) end
function lovr.filesystem.getExecutablePath() end
---
----Returns the identity of the game, which is used as the name of the save directory. The default is `default`. It can be changed using `t.identity` in `lovr.conf`.
+---Returns the identity of the game, which is used as the name of the save directory.
+---
+---The default is `default`.
+---
+---It can be changed using `t.identity` in `lovr.conf`.
+---
+---
+---### NOTE:
+---On Android, this is always the package id (like `org.lovr.app`).
---
---@return string identity # The name of the save directory, or `nil` if it isn't set.
function lovr.filesystem.getIdentity() end
@@ -59,14 +103,26 @@ function lovr.filesystem.getIdentity() end
function lovr.filesystem.getLastModified(path) end
---
----Get the absolute path of the mounted archive containing a path in the virtual filesystem. This can be used to determine if a file is in the game's source directory or the save directory.
+---Get the absolute path of the mounted archive containing a path in the virtual filesystem.
+---
+---This can be used to determine if a file is in the game's source directory or the save directory.
---
---@param path string # The path to check.
---@return string realpath # The absolute path of the mounted archive containing `path`.
function lovr.filesystem.getRealDirectory(path) end
---
----Returns the require path. The require path is a semicolon-separated list of patterns that LÖVR will use to search for files when they are `require`d. Any question marks in the pattern will be replaced with the module that is being required. It is similar to Lua\'s `package.path` variable, but the main difference is that the patterns are relative to the virtual filesystem.
+---Returns the require path.
+---
+---The require path is a semicolon-separated list of patterns that LÖVR will use to search for files when they are `require`d.
+---
+---Any question marks in the pattern will be replaced with the module that is being required.
+---
+---It is similar to Lua\'s `package.path` variable, but the main difference is that the patterns are relative to the virtual filesystem.
+---
+---
+---### NOTE:
+---The default reqiure path is '?.lua;?/init.lua'.
---
---@return string path # The semicolon separated list of search patterns.
function lovr.filesystem.getRequirePath() end
@@ -74,12 +130,24 @@ function lovr.filesystem.getRequirePath() end
---
---Returns the absolute path to the save directory.
---
+---
+---### NOTE:
+---The save directory takes the following form:
+---
+---``` <appdata>/LOVR/<identity> ```
+---
+---Where `<appdata>` is `lovr.filesystem.getAppdataDirectory` and `<identity>` is `lovr.filesystem.getIdentity` and can be customized using `lovr.conf`.
+---
---@return string path # The absolute path to the save directory.
function lovr.filesystem.getSaveDirectory() end
---
---Returns the size of a file, in bytes.
---
+---
+---### NOTE:
+---If the file does not exist, an error is thrown.
+---
---@param file string # The file.
---@return number size # The size of the file, in bytes.
function lovr.filesystem.getSize(file) end
@@ -97,7 +165,9 @@ function lovr.filesystem.getSource() end
function lovr.filesystem.getUserDirectory() end
---
----Returns the absolute path of the working directory. Usually this is where the executable was started from.
+---Returns the absolute path of the working directory.
+---
+---Usually this is where the executable was started from.
---
---@return string path # The current working directory, or `nil` if it's unknown.
function lovr.filesystem.getWorkingDirectory() end
@@ -125,12 +195,26 @@ function lovr.filesystem.isFused() end
---
---Load a file containing Lua code, returning a Lua chunk that can be run.
---
+---
+---### NOTE:
+---An error is thrown if the file contains syntax errors.
+---
---@param filename string # The file to load.
---@return function chunk # The runnable chunk.
function lovr.filesystem.load(filename) end
---
----Mounts a directory or `.zip` archive, adding it to the virtual filesystem. This allows you to read files from it.
+---Mounts a directory or `.zip` archive, adding it to the virtual filesystem.
+---
+---This allows you to read files from it.
+---
+---
+---### NOTE:
+---The `append` option lets you control the priority of the archive's files in the event of naming collisions.
+---
+---This function is not thread safe.
+---
+---Mounting or unmounting an archive while other threads call lovr.filesystem functions is not supported.
---
---@param path string # The path to mount.
---@param mountpoint? string # The path in the virtual filesystem to mount to.
@@ -149,6 +233,10 @@ function lovr.filesystem.newBlob(filename) end
---
---Read the contents of a file.
---
+---
+---### NOTE:
+---If the file does not exist or cannot be read, nil is returned.
+---
---@param filename string # The name of the file to read.
---@param bytes? number # The number of bytes to read (if -1, all bytes will be read).
---@return string contents # The contents of the file.
@@ -158,6 +246,12 @@ function lovr.filesystem.read(filename, bytes) end
---
---Remove a file or directory in the save directory.
---
+---
+---### NOTE:
+---A directory can only be removed if it is empty.
+---
+---To recursively remove a folder, use this function with `lovr.filesystem.getDirectoryItems`.
+---
---@param path string # The file or directory to remove.
---@return boolean success # Whether the path was removed.
function lovr.filesystem.remove(path) end
@@ -169,13 +263,25 @@ function lovr.filesystem.remove(path) end
function lovr.filesystem.setIdentity(identity) end
---
----Sets the require path. The require path is a semicolon-separated list of patterns that LÖVR will use to search for files when they are `require`d. Any question marks in the pattern will be replaced with the module that is being required. It is similar to Lua\'s `package.path` variable, but the main difference is that the patterns are relative to the save directory and the project directory.
+---Sets the require path.
+---
+---The require path is a semicolon-separated list of patterns that LÖVR will use to search for files when they are `require`d.
+---
+---Any question marks in the pattern will be replaced with the module that is being required.
+---
+---It is similar to Lua\'s `package.path` variable, but the main difference is that the patterns are relative to the save directory and the project directory.
+---
+---
+---### NOTE:
+---The default reqiure path is '?.lua;?/init.lua'.
---
---@param path? string # An optional semicolon separated list of search patterns.
function lovr.filesystem.setRequirePath(path) end
---
----Sets the location of the project's source. This can only be done once, and is usually done internally.
+---Sets the location of the project's source.
+---
+---This can only be done once, and is usually done internally.
---
---@param identity string # The path containing the project's source.
function lovr.filesystem.setSource(identity) end
@@ -183,6 +289,12 @@ function lovr.filesystem.setSource(identity) end
---
---Unmounts a directory or archive previously mounted with `lovr.filesystem.mount`.
---
+---
+---### NOTE:
+---This function is not thread safe.
+---
+---Mounting or unmounting an archive while other threads call lovr.filesystem functions is not supported.
+---
---@param path string # The path to unmount.
---@return boolean success # Whether the archive was unmounted.
function lovr.filesystem.unmount(path) end
@@ -190,6 +302,12 @@ function lovr.filesystem.unmount(path) end
---
---Write to a file.
---
+---
+---### NOTE:
+---If the file does not exist, it is created.
+---
+---If the file already has data in it, it will be replaced with the new content.
+---
---@overload fun(filename: string, blob: lovr.Blob):number
---@param filename string # The file to write to.
---@param content string # A string to write to the file.
diff --git a/meta/3rd/lovr/library/lovr.graphics.lua b/meta/3rd/lovr/library/lovr.graphics.lua
index 788126f7..f0ccb310 100644
--- a/meta/3rd/lovr/library/lovr.graphics.lua
+++ b/meta/3rd/lovr/library/lovr.graphics.lua
@@ -1,7 +1,9 @@
---@meta
---
----The `lovr.graphics` module renders graphics to displays. Anything rendered using this module will automatically show up in the VR headset if one is connected, otherwise it will just show up in a window on the desktop.
+---The `lovr.graphics` module renders graphics to displays.
+---
+---Anything rendered using this module will automatically show up in the VR headset if one is connected, otherwise it will just show up in a window on the desktop.
---
---@class lovr.graphics
lovr.graphics = {}
@@ -9,6 +11,10 @@ lovr.graphics = {}
---
---Draws an arc.
---
+---
+---### NOTE:
+---The local normal vector of the circle is `(0, 0, 1)`.
+---
---@overload fun(material: lovr.Material, x: number, y: number, z: number, radius: number, angle: number, ax: number, ay: number, az: number, start: number, end: number, segments: number)
---@overload fun(mode: lovr.DrawStyle, transform: lovr.mat4, start: number, end: number, segments: number)
---@overload fun(material: lovr.Material, transform: lovr.mat4, start: number, end: number, segments: number)
@@ -31,7 +37,9 @@ lovr.graphics = {}
function lovr.graphics.arc(mode, x, y, z, radius, angle, ax, ay, az, start, end, segments) end
---
----Draws a box. This is similar to `lovr.graphics.cube` except you can have different values for the width, height, and depth of the box.
+---Draws a box.
+---
+---This is similar to `lovr.graphics.cube` except you can have different values for the width, height, and depth of the box.
---
---@overload fun(material: lovr.Material, x: number, y: number, z: number, width: number, height: number, depth: number, angle: number, ax: number, ay: number, az: number)
---@overload fun(mode: lovr.DrawStyle, transform: lovr.mat4)
@@ -52,6 +60,10 @@ function lovr.graphics.box(mode, x, y, z, width, height, depth, angle, ax, ay, a
---
---Draws a 2D circle.
---
+---
+---### NOTE:
+---The local normal vector of the circle is `(0, 0, 1)`.
+---
---@overload fun(material: lovr.Material, x: number, y: number, z: number, radius: number, angle: number, ax: number, ay: number, az: number, segments: number)
---@overload fun(mode: lovr.DrawStyle, transform: lovr.mat4, segments: number)
---@overload fun(material: lovr.Material, transform: lovr.mat4, segments: number)
@@ -68,7 +80,15 @@ function lovr.graphics.box(mode, x, y, z, width, height, depth, angle, ax, ay, a
function lovr.graphics.circle(mode, x, y, z, radius, angle, ax, ay, az, segments) end
---
----Clears the screen, resetting the color, depth, and stencil information to default values. This function is called automatically by `lovr.run` at the beginning of each frame to clear out the data from the previous frame.
+---Clears the screen, resetting the color, depth, and stencil information to default values.
+---
+---This function is called automatically by `lovr.run` at the beginning of each frame to clear out the data from the previous frame.
+---
+---
+---### NOTE:
+---The first two variants of this function can be mixed and matched, meaning you can use booleans for some of the values and numeric values for others.
+---
+---If you are using `lovr.graphics.setStencilTest`, it will not affect how the screen gets cleared. Instead, you can use `lovr.graphics.fill` to draw a fullscreen quad, which will get masked by the active stencil.
---
---@overload fun(r: number, g: number, b: number, a: number, z: number, s: number)
---@overload fun(hex: number)
@@ -78,10 +98,18 @@ function lovr.graphics.circle(mode, x, y, z, radius, angle, ax, ay, az, segments
function lovr.graphics.clear(color, depth, stencil) end
---
----This function runs a compute shader on the GPU. Compute shaders must be created with `lovr.graphics.newComputeShader` and they should implement the `void compute();` GLSL function. Running a compute shader doesn't actually do anything, but the Shader can modify data stored in `Texture`s or `ShaderBlock`s to get interesting things to happen.
+---This function runs a compute shader on the GPU.
+---
+---Compute shaders must be created with `lovr.graphics.newComputeShader` and they should implement the `void compute();` GLSL function. Running a compute shader doesn't actually do anything, but the Shader can modify data stored in `Texture`s or `ShaderBlock`s to get interesting things to happen.
---
---When running the compute shader, you can specify the number of times to run it in 3 dimensions, which is useful to iterate over large numbers of elements like pixels or array elements.
---
+---
+---### NOTE:
+---Only compute shaders created with `lovr.graphics.newComputeShader` can be used here.
+---
+---There are GPU-specific limits on the `x`, `y`, and `z` values which can be queried in the `compute` entry of `lovr.graphics.getLimits`.
+---
---@param shader lovr.Shader # The compute shader to run.
---@param x? number # The amount of times to run in the x direction.
---@param y? number # The amount of times to run in the y direction.
@@ -91,6 +119,16 @@ function lovr.graphics.compute(shader, x, y, z) end
---
---Create the desktop window, usually used to mirror the headset display.
---
+---
+---### NOTE:
+---This function can only be called once.
+---
+---It is normally called internally, but you can override this by setting window to `nil` in conf.lua.
+---
+---See `lovr.conf` for more information.
+---
+---The window must be created before any `lovr.graphics` functions can be used.
+---
---@param flags {width: number, height: number, fullscreen: boolean, resizable: boolean, msaa: number, title: string, icon: string, vsync: number} # Flags to customize the window's appearance and behavior.
function lovr.graphics.createWindow(flags) end
@@ -114,6 +152,10 @@ function lovr.graphics.cube(mode, x, y, z, size, angle, ax, ay, az) end
---
---Draws a cylinder.
---
+---
+---### NOTE:
+---Currently, cylinders don't have UVs.
+---
---@overload fun(material: lovr.Material, x: number, y: number, z: number, length: number, angle: number, ax: number, ay: number, az: number, r1: number, r2: number, capped: boolean, segments: number)
---@param x? number # The x coordinate of the center of the cylinder.
---@param y? number # The y coordinate of the center of the cylinder.
@@ -130,7 +172,9 @@ function lovr.graphics.cube(mode, x, y, z, size, angle, ax, ay, az) end
function lovr.graphics.cylinder(x, y, z, length, angle, ax, ay, az, r1, r2, capped, segments) end
---
----Discards pixel information in the active Canvas or display. This is mostly used as an optimization hint for the GPU, and is usually most helpful on mobile devices.
+---Discards pixel information in the active Canvas or display.
+---
+---This is mostly used as an optimization hint for the GPU, and is usually most helpful on mobile devices.
---
---@param color? boolean # Whether or not to discard color information.
---@param depth? boolean # Whether or not to discard depth information.
@@ -140,6 +184,12 @@ function lovr.graphics.discard(color, depth, stencil) end
---
---Draws a fullscreen textured quad.
---
+---
+---### NOTE:
+---This function ignores stereo rendering, so it will stretch the input across the entire Canvas if it's stereo.
+---
+---Special shaders are currently required for correct stereo fills.
+---
---@overload fun()
---@param texture lovr.Texture # The texture to use.
---@param u? number # The x component of the uv offset.
@@ -149,18 +199,37 @@ function lovr.graphics.discard(color, depth, stencil) end
function lovr.graphics.fill(texture, u, v, w, h) end
---
----Flushes the internal queue of draw batches. Under normal circumstances this is done automatically when needed, but the ability to flush manually may be helpful if you're integrating a LÖVR project with some external rendering code.
+---Flushes the internal queue of draw batches.
+---
+---Under normal circumstances this is done automatically when needed, but the ability to flush manually may be helpful if you're integrating a LÖVR project with some external rendering code.
---
function lovr.graphics.flush() end
---
----Returns whether or not alpha sampling is enabled. Alpha sampling is also known as alpha-to-coverage. When it is enabled, the alpha channel of a pixel is factored into how antialiasing is computed, so the edges of a transparent texture will be correctly antialiased.
+---Returns whether or not alpha sampling is enabled.
+---
+---Alpha sampling is also known as alpha-to-coverage.
+---
+---When it is enabled, the alpha channel of a pixel is factored into how antialiasing is computed, so the edges of a transparent texture will be correctly antialiased.
+---
+---
+---### NOTE:
+---- Alpha sampling is disabled by default.
+---- This feature can be used for a simple transparency effect, pixels with an alpha of zero will
+--- have their depth value discarded, allowing things behind them to show through (normally you
+--- have to sort objects or write a shader for this).
---
---@return boolean enabled # Whether or not alpha sampling is enabled.
function lovr.graphics.getAlphaSampling() end
---
----Returns the current background color. Color components are from 0.0 to 1.0.
+---Returns the current background color.
+---
+---Color components are from 0.0 to 1.0.
+---
+---
+---### NOTE:
+---The default background color is `(0.0, 0.0, 0.0, 1.0)`.
---
---@return number r # The red component of the background color.
---@return number g # The green component of the background color.
@@ -169,22 +238,40 @@ function lovr.graphics.getAlphaSampling() end
function lovr.graphics.getBackgroundColor() end
---
----Returns the current blend mode. The blend mode controls how each pixel's color is blended with the previous pixel's color when drawn.
+---Returns the current blend mode.
+---
+---The blend mode controls how each pixel's color is blended with the previous pixel's color when drawn.
---
---If blending is disabled, `nil` will be returned.
---
+---
+---### NOTE:
+---The default blend mode is `alpha` and `alphamultiply`.
+---
---@return lovr.BlendMode blend # The current blend mode.
---@return lovr.BlendAlphaMode alphaBlend # The current alpha blend mode.
function lovr.graphics.getBlendMode() end
---
----Returns the active Canvas. Usually when you render something it will render directly to the headset. If a Canvas object is active, things will be rendered to the textures attached to the Canvas instead.
+---Returns the active Canvas.
+---
+---Usually when you render something it will render directly to the headset.
+---
+---If a Canvas object is active, things will be rendered to the textures attached to the Canvas instead.
---
---@return lovr.Canvas canvas # The active Canvas, or `nil` if no canvas is set.
function lovr.graphics.getCanvas() end
---
----Returns the current global color factor. Color components are from 0.0 to 1.0. Every pixel drawn will be multiplied (i.e. tinted) by this color.
+---Returns the current global color factor.
+---
+---Color components are from 0.0 to 1.0.
+---
+---Every pixel drawn will be multiplied (i.e. tinted) by this color.
+---
+---
+---### NOTE:
+---The default color is `(1.0, 1.0, 1.0, 1.0)`.
---
---@return number r # The red component of the color.
---@return number g # The green component of the color.
@@ -193,12 +280,26 @@ function lovr.graphics.getCanvas() end
function lovr.graphics.getColor() end
---
----Returns a boolean for each color channel (red, green, blue, alpha) indicating whether it is enabled. When a color channel is enabled, it will be affected by drawing commands and clear commands.
+---Returns a boolean for each color channel (red, green, blue, alpha) indicating whether it is enabled.
+---
+---When a color channel is enabled, it will be affected by drawing commands and clear commands.
+---
+---
+---### NOTE:
+---By default, all color channels are enabled.
+---
+---Disabling all of the color channels can be useful if you only want to write to the depth buffer or the stencil buffer.
---
function lovr.graphics.getColorMask() end
---
----Returns the default filter mode for new Textures. This controls how textures are sampled when they are minified, magnified, or stretched.
+---Returns the default filter mode for new Textures.
+---
+---This controls how textures are sampled when they are minified, magnified, or stretched.
+---
+---
+---### NOTE:
+---The default filter is `trilinear`.
---
---@return lovr.FilterMode mode # The filter mode.
---@return number anisotropy # The level of anisotropy.
@@ -207,6 +308,28 @@ function lovr.graphics.getDefaultFilter() end
---
---Returns the current depth test settings.
---
+---
+---### NOTE:
+---The depth test is an advanced technique to control how 3D objects overlap each other when they are rendered.
+---
+---It works as follows:
+---
+---- Each pixel keeps track of its z value as well as its color.
+---- If `write` is enabled when something is drawn, then any pixels that are drawn will have their
+--- z values updated.
+---- Additionally, anything drawn will first compare the existing z value of a pixel with the new z
+--- value.
+---
+---The `compareMode` setting determines how this comparison is performed.
+---
+---If the
+--- comparison succeeds, the new pixel will overwrite the previous one, otherwise that pixel won't
+--- be rendered to.
+---
+---Smaller z values are closer to the camera.
+---
+---The default compare mode is `lequal`, which usually gives good results for normal 3D rendering.
+---
---@return lovr.CompareMode compareMode # The current comparison method for depth testing.
---@return boolean write # Whether pixels will have their z value updated when rendered to.
function lovr.graphics.getDepthTest() end
@@ -245,11 +368,23 @@ function lovr.graphics.getLimits() end
---
---Returns the current line width.
---
+---
+---### NOTE:
+---The default line width is `1`.
+---
---@return number width # The current line width, in pixels.
function lovr.graphics.getLineWidth() end
---
----Returns the pixel density of the window. On "high-dpi" displays, this will be `2.0`, indicating that there are 2 pixels for every window coordinate. On a normal display it will be `1.0`, meaning that the pixel to window-coordinate ratio is 1:1.
+---Returns the pixel density of the window.
+---
+---On "high-dpi" displays, this will be `2.0`, indicating that there are 2 pixels for every window coordinate.
+---
+---On a normal display it will be `1.0`, meaning that the pixel to window-coordinate ratio is 1:1.
+---
+---
+---### NOTE:
+---If the window isn't created yet, this function will return 0.
---
---@return number density # The pixel density of the window.
function lovr.graphics.getPixelDensity() end
@@ -257,12 +392,24 @@ function lovr.graphics.getPixelDensity() end
---
---Returns the current point size.
---
+---
+---### NOTE:
+---The default point size is `1.0`.
+---
---@return number size # The current point size, in pixels.
function lovr.graphics.getPointSize() end
---
---Returns the projection for a single view.
---
+---
+---### NOTE:
+---Non-stereo rendering will only use the first view.
+---
+---The projection matrices are available as the `mat4 lovrProjections[2]` variable in shaders.
+---
+---The current projection matrix is available as `lovrProjection`.
+---
---@overload fun(view: number, matrix: lovr.Mat4):lovr.Mat4
---@param view number # The view index.
---@return number left # The left field of view angle, in radians.
@@ -284,7 +431,19 @@ function lovr.graphics.getShader() end
function lovr.graphics.getStats() end
---
----Returns the current stencil test. The stencil test lets you mask out pixels that meet certain criteria, based on the contents of the stencil buffer. The stencil buffer can be modified using `lovr.graphics.stencil`. After rendering to the stencil buffer, the stencil test can be set to control how subsequent drawing functions are masked by the stencil buffer.
+---Returns the current stencil test.
+---
+---The stencil test lets you mask out pixels that meet certain criteria, based on the contents of the stencil buffer.
+---
+---The stencil buffer can be modified using `lovr.graphics.stencil`.
+---
+---After rendering to the stencil buffer, the stencil test can be set to control how subsequent drawing functions are masked by the stencil buffer.
+---
+---
+---### NOTE:
+---Stencil values are between 0 and 255.
+---
+---By default, the stencil test is disabled.
---
---@return lovr.CompareMode compareMode # The comparison method used to decide if a pixel should be visible, or nil if the stencil test is disabled.
---@return number compareValue # The value stencil values are compared against, or nil if the stencil test is disabled.
@@ -311,7 +470,17 @@ function lovr.graphics.getViewPose(view) end
function lovr.graphics.getWidth() end
---
----Returns the current polygon winding. The winding direction determines which face of a triangle is the front face and which is the back face. This lets the graphics engine cull the back faces of polygons, improving performance.
+---Returns the current polygon winding.
+---
+---The winding direction determines which face of a triangle is the front face and which is the back face.
+---
+---This lets the graphics engine cull the back faces of polygons, improving performance.
+---
+---
+---### NOTE:
+---Culling is initially disabled and must be enabled using `lovr.graphics.setCullingEnabled`.
+---
+---The default winding direction is counterclockwise.
---
---@return lovr.Winding winding # The current winding direction.
function lovr.graphics.getWinding() end
@@ -319,11 +488,23 @@ function lovr.graphics.getWinding() end
---
---Returns whether the desktop window is currently created.
---
+---
+---### NOTE:
+---Most of the `lovr.graphics` functionality will only work if a window is created.
+---
---@return boolean present # Whether a window is created.
function lovr.graphics.hasWindow() end
---
----Returns whether or not culling is active. Culling is an optimization that avoids rendering the back face of polygons. This improves performance by reducing the number of polygons drawn, but requires that the vertices in triangles are specified in a consistent clockwise or counter clockwise order.
+---Returns whether or not culling is active.
+---
+---Culling is an optimization that avoids rendering the back face of polygons.
+---
+---This improves performance by reducing the number of polygons drawn, but requires that the vertices in triangles are specified in a consistent clockwise or counter clockwise order.
+---
+---
+---### NOTE:
+---Culling is disabled by default.
---
---@return boolean isEnabled # Whether or not culling is enabled.
function lovr.graphics.isCullingEnabled() end
@@ -331,11 +512,19 @@ function lovr.graphics.isCullingEnabled() end
---
---Returns a boolean indicating whether or not wireframe rendering is enabled.
---
+---
+---### NOTE:
+---Wireframe rendering is initially disabled.
+---
+---Wireframe rendering is only supported on desktop systems.
+---
---@return boolean isWireframe # Whether or not wireframe rendering is enabled.
function lovr.graphics.isWireframe() end
---
----Draws lines between points. Each point will be connected to the previous point in the list.
+---Draws lines between points.
+---
+---Each point will be connected to the previous point in the list.
---
---@overload fun(points: table)
---@param x1 number # The x coordinate of the first point.
@@ -347,10 +536,18 @@ function lovr.graphics.isWireframe() end
function lovr.graphics.line(x1, y1, z1, x2, y2, z2) end
---
----Creates a new Canvas. You can specify Textures to attach to it, or just specify a width and height and attach textures later using `Canvas:setTexture`.
+---Creates a new Canvas.
+---
+---You can specify Textures to attach to it, or just specify a width and height and attach textures later using `Canvas:setTexture`.
---
---Once created, you can render to the Canvas using `Canvas:renderTo`, or `lovr.graphics.setCanvas`.
---
+---
+---### NOTE:
+---Textures created by this function will have `clamp` as their `WrapMode`.
+---
+---Stereo Canvases will either have their width doubled or use array textures for their attachments, depending on their implementation.
+---
---@overload fun(..., flags: table):lovr.Canvas
---@overload fun(attachments: table, flags: table):lovr.Canvas
---@param width number # The width of the canvas, in pixels.
@@ -362,16 +559,32 @@ function lovr.graphics.newCanvas(width, height, flags) end
---
---Creates a new compute Shader, used for running generic compute operations on the GPU.
---
+---
+---### NOTE:
+---Compute shaders are not supported on all hardware, use `lovr.graphics.getFeatures` to check if they're available on the current system.
+---
+---The source code for a compute shader needs to implement the `void compute();` GLSL function. This function doesn't return anything, but the compute shader is able to write data out to `Texture`s or `ShaderBlock`s.
+---
+---The GLSL version used for compute shaders is GLSL 430.
+---
+---Currently, up to 32 shader flags are supported.
+---
---@param source string # The code or filename of the compute shader.
---@param options? {flags: table} # Optional settings for the Shader.
---@return lovr.Shader shader # The new compute Shader.
function lovr.graphics.newComputeShader(source, options) end
---
----Creates a new Font. It can be used to render text with `lovr.graphics.print`.
+---Creates a new Font.
+---
+---It can be used to render text with `lovr.graphics.print`.
---
---Currently, the only supported font format is TTF.
---
+---
+---### NOTE:
+---Larger font sizes will lead to more detailed curves at the cost of performance.
+---
---@overload fun(size: number, padding: number, spread: number):lovr.Font
---@overload fun(rasterizer: lovr.Rasterizer, padding: number, spread: number):lovr.Font
---@param filename string # The filename of the font file.
@@ -382,7 +595,18 @@ function lovr.graphics.newComputeShader(source, options) end
function lovr.graphics.newFont(filename, size, padding, spread) end
---
----Creates a new Material. Materials are sets of colors, textures, and other parameters that affect the appearance of objects. They can be applied to `Model`s, `Mesh`es, and most graphics primitives accept a Material as an optional first argument.
+---Creates a new Material.
+---
+---Materials are sets of colors, textures, and other parameters that affect the appearance of objects.
+---
+---They can be applied to `Model`s, `Mesh`es, and most graphics primitives accept a Material as an optional first argument.
+---
+---
+---### NOTE:
+---- Scalar properties will default to `1.0`.
+---- Color properties will default to `(1.0, 1.0, 1.0, 1.0)`, except for `emissive` which will
+--- default to `(0.0, 0.0, 0.0, 0.0)`.
+---- Textures will default to `nil` (a single 1x1 white pixel will be used for them).
---
---@overload fun(texture: lovr.Texture, r: number, g: number, b: number, a: number):lovr.Material
---@overload fun(canvas: lovr.Canvas, r: number, g: number, b: number, a: number):lovr.Material
@@ -392,10 +616,28 @@ function lovr.graphics.newFont(filename, size, padding, spread) end
function lovr.graphics.newMaterial() end
---
----Creates a new Mesh. Meshes contain the data for an arbitrary set of vertices, and can be drawn. You must specify either the capacity for the Mesh or an initial set of vertex data. Optionally, a custom format table can be used to specify the set of vertex attributes the mesh will provide to the active shader. The draw mode and usage hint can also optionally be specified.
+---Creates a new Mesh.
+---
+---Meshes contain the data for an arbitrary set of vertices, and can be drawn. You must specify either the capacity for the Mesh or an initial set of vertex data.
+---
+---Optionally, a custom format table can be used to specify the set of vertex attributes the mesh will provide to the active shader.
+---
+---The draw mode and usage hint can also optionally be specified.
---
---The default data type for an attribute is `float`, and the default component count is 1.
---
+---
+---### NOTE:
+---Once created, the size and format of the Mesh cannot be changed.'
+---
+---The default mesh format is:
+---
+--- {
+--- { 'lovrPosition', 'float', 3 },
+--- { 'lovrNormal', 'float', 3 },
+--- { 'lovrTexCoord', 'float', 2 }
+--- }
+---
---@overload fun(vertices: table, mode: lovr.DrawMode, usage: lovr.MeshUsage, readable: boolean):lovr.Mesh
---@overload fun(blob: lovr.Blob, mode: lovr.DrawMode, usage: lovr.MeshUsage, readable: boolean):lovr.Mesh
---@overload fun(format: table, size: number, mode: lovr.DrawMode, usage: lovr.MeshUsage, readable: boolean):lovr.Mesh
@@ -409,7 +651,23 @@ function lovr.graphics.newMaterial() end
function lovr.graphics.newMesh(size, mode, usage, readable) end
---
----Creates a new Model from a file. The supported 3D file formats are OBJ, glTF, and STL.
+---Creates a new Model from a file.
+---
+---The supported 3D file formats are OBJ, glTF, and STL.
+---
+---
+---### NOTE:
+---Diffuse and emissive textures will be loaded in the sRGB encoding, all other textures will be loaded as linear.
+---
+---Currently, the following features are not supported by the model importer:
+---
+---- OBJ: Quads are not supported (only triangles).
+---- glTF: Sparse accessors are not supported.
+---- glTF: Morph targets are not supported.
+---- glTF: base64 images are not supported (base64 buffer data works though).
+---- glTF: Only the default scene is loaded.
+---- glTF: Currently, each skin in a Model can have up to 48 joints.
+---- STL: ASCII STL files are not supported.
---
---@overload fun(modelData: lovr.ModelData):lovr.Model
---@param filename string # The filename of the model to load.
@@ -419,6 +677,87 @@ function lovr.graphics.newModel(filename) end
---
---Creates a new Shader.
---
+---
+---### NOTE:
+---The `flags` table should contain string keys, with boolean or numeric values.
+---
+---These flags can be used to customize the behavior of Shaders from Lua, by using the flags in the shader source code.
+---
+---Numeric flags will be available as constants named `FLAG_<flagName>`.
+---
+---Boolean flags can be used with `#ifdef` and will only be defined if the value in the Lua table was `true`.
+---
+---The following flags are used by shaders provided by LÖVR:
+---
+---- `animated` is a boolean flag that will cause the shader to position vertices based on the pose
+--- of an animated skeleton.
+---
+---This should usually only be used for animated `Model`s, since it
+--- needs a skeleton to work properly and is slower than normal rendering.
+---- `alphaCutoff` is a numeric flag that can be used to implement simple "cutout" style
+--- transparency, where pixels with alpha below a certain threshold will be discarded.
+---
+---The value
+--- of the flag should be a number between 0.0 and 1.0, representing the alpha threshold.
+---- `uniformScale` is a boolean flag used for optimization.
+---
+---If the Shader is only going to be
+--- used with objects that have a *uniform* scale (i.e. the x, y, and z components of the scale
+--- are all the same number), then this flag can be set to use a faster method to compute the
+--- `lovrNormalMatrix` uniform variable.
+---- `multicanvas` is a boolean flag that should be set when rendering to multiple Textures
+--- attached to a `Canvas`.
+---
+---When set, the fragment shader should implement the `colors` function
+--- instead of the `color` function, and can write color values to the `lovrCanvas` array instead
+--- of returning a single color.
+---
+---Each color in the array gets written to the corresponding
+--- texture attached to the canvas.
+---- `highp` is a boolean flag specific to mobile GPUs that changes the default precision for
+--- fragment shaders to use high precision instead of the default medium precision.
+---
+---This can fix
+--- visual issues caused by a lack of precision, but isn't guaranteed to be supported on some
+--- lower-end systems.
+---- The following flags are used only by the `standard` PBR shader:
+--- - `normalMap` should be set to `true` to render objects with a normal map, providing a more
+--- detailed, bumpy appearance.
+---
+---Currently, this requires the model to have vertex tangents.
+--- - `emissive` should be set to `true` to apply emissive maps to rendered objects.
+---
+---This is
+--- usually used to apply glowing lights or screens to objects, since the emissive texture is
+--- not affected at all by lighting.
+--- - `indirectLighting` is an *awesome* boolean flag that will apply realistic reflections and
+--- lighting to the surface of an object, based on a specially-created skybox.
+---
+---See the
+--- `Standard Shader` guide for more information.
+--- - `occlusion` is a boolean flag that uses the ambient occlusion texture in the model.
+---
+---It only
+--- affects indirect lighting, so it will only have an effect if the `indirectLighting` flag is
+--- also enabled.
+--- - `skipTonemap` is a flag that will skip the tonemapping process.
+---
+---Tonemapping is an important
+--- process that maps the high definition physical color values down to a 0 - 1 range for
+--- display.
+---
+---There are lots of different tonemapping algorithms that give different artistic
+--- effects.
+---
+---The default tonemapping in the standard shader is the ACES algorithm, but you can
+--- use this flag to turn off ACES and use your own tonemapping.
+---
+---Currently, up to 32 shader flags are supported.
+---
+---The `stereo` option is only necessary for Android.
+---
+---Currently on Android, only stereo shaders can be used with stereo Canvases, and mono Shaders can only be used with mono Canvases.
+---
---@overload fun(default: lovr.DefaultShader, options: table):lovr.Shader
---@param vertex string # The code or filename of the vertex shader. If nil, the default vertex shader is used.
---@param fragment string # The code or filename of the fragment shader. If nil, the default fragment shader is used.
@@ -429,6 +768,14 @@ function lovr.graphics.newShader(vertex, fragment, options) end
---
---Creates a new ShaderBlock from a table of variable definitions with their names and types.
---
+---
+---### NOTE:
+---`compute` blocks can only be true if compute shaders are supported, see `lovr.graphics.getFeatures`.
+---
+---Compute blocks may be slightly slower than uniform blocks, but they can also be much, much larger.
+---
+---Uniform blocks are usually limited to around 16 kilobytes in size, depending on hardware.
+---
---@param type lovr.BlockType # Whether the block will be used for read-only uniform data or compute shaders.
---@param uniforms table # A table where the keys are uniform names and the values are uniform types. Uniform arrays can be specified by supplying a table as the uniform's value containing the type and the array size.
---@param flags? {usage: lovr.BufferUsage, readable: boolean} # Optional settings.
@@ -438,6 +785,12 @@ function lovr.graphics.newShaderBlock(type, uniforms, flags) end
---
---Creates a new Texture from an image file.
---
+---
+---### NOTE:
+---The "linear" flag should be set to true for textures that don't contain color information, such as normal maps.
+---
+---Right now the supported image file formats are png, jpg, hdr, dds (DXT1, DXT3, DXT5), ktx, and astc.
+---
---@overload fun(images: table, flags: table):lovr.Texture
---@overload fun(width: number, height: number, depth: number, flags: table):lovr.Texture
---@overload fun(blob: lovr.Blob, flags: table):lovr.Texture
@@ -450,11 +803,21 @@ function lovr.graphics.newTexture(filename, flags) end
---
---Resets the transformation to the origin.
---
+---
+---### NOTE:
+---This is called at the beginning of every frame to reset the coordinate space.
+---
function lovr.graphics.origin() end
---
---Draws a plane with a given position, size, and orientation.
---
+---
+---### NOTE:
+---The `u`, `v`, `w`, `h` arguments can be used to select a subregion of the diffuse texture to apply to the plane.
+---
+---One efficient technique for rendering many planes with different textures is to pack all of the textures into a single image, and then use the uv arguments to select a sub-rectangle to use for each plane.
+---
---@overload fun(material: lovr.Material, x: number, y: number, z: number, width: number, height: number, angle: number, ax: number, ay: number, az: number, u: number, v: number, w: number, h: number)
---@param mode lovr.DrawStyle # How to draw the plane.
---@param x? number # The x coordinate of the center of the plane.
@@ -484,16 +847,40 @@ function lovr.graphics.points(x, y, z) end
---
---Pops the current transform from the stack, returning to the transformation that was applied before `lovr.graphics.push` was called.
---
+---
+---### NOTE:
+---An error is thrown if there isn't a transform to pop.
+---
+---This can happen if you forget to call push before calling pop, or if you have an unbalanced sequence of pushes and pops.
+---
function lovr.graphics.pop() end
---
----Presents the results of pending drawing operations to the window. This is automatically called after `lovr.draw` by the default `lovr.run` function.
+---Presents the results of pending drawing operations to the window.
+---
+---This is automatically called after `lovr.draw` by the default `lovr.run` function.
---
function lovr.graphics.present() end
---
---Draws text in 3D space using the active font.
---
+---
+---### NOTE:
+---Unicode text is supported.
+---
+---Use `\n` to add line breaks.
+---
+---`\t` will be rendered as four spaces.
+---
+---LÖVR uses a fancy technique for font rendering called multichannel signed distance fields.
+---
+---This leads to crisp text in VR, but requires a special shader to use.
+---
+---LÖVR internally switches to the appropriate shader, but only when the default shader is already set.
+---
+---If you see strange font artifacts, make sure you switch back to the default shader by using `lovr.graphics.setShader()` before you draw text.
+---
---@param str string # The text to render.
---@param x? number # The x coordinate of the center of the text.
---@param y? number # The y coordinate of the center of the text.
@@ -509,7 +896,15 @@ function lovr.graphics.present() end
function lovr.graphics.print(str, x, y, z, scale, angle, ax, ay, az, wrap, halign, valign) end
---
----Pushes a copy of the current transform onto the transformation stack. After changing the transform using `lovr.graphics.translate`, `lovr.graphics.rotate`, and `lovr.graphics.scale`, the original state can be restored using `lovr.graphics.pop`.
+---Pushes a copy of the current transform onto the transformation stack.
+---
+---After changing the transform using `lovr.graphics.translate`, `lovr.graphics.rotate`, and `lovr.graphics.scale`, the original state can be restored using `lovr.graphics.pop`.
+---
+---
+---### NOTE:
+---An error is thrown if more than 64 matrices are pushed.
+---
+---This can happen accidentally if a push isn't followed by a corresponding pop.
---
function lovr.graphics.push() end
@@ -523,6 +918,10 @@ function lovr.graphics.reset() end
---
---The rotation will last until `lovr.draw` returns or the transformation is popped off the transformation stack.
---
+---
+---### NOTE:
+---Order matters when scaling, translating, and rotating the coordinate system.
+---
---@param angle? number # The amount to rotate the coordinate system by, in radians.
---@param ax? number # The x component of the axis of rotation.
---@param ay? number # The y component of the axis of rotation.
@@ -530,23 +929,46 @@ function lovr.graphics.reset() end
function lovr.graphics.rotate(angle, ax, ay, az) end
---
----Scales the coordinate system in 3 dimensions. This will cause objects to appear bigger or smaller.
+---Scales the coordinate system in 3 dimensions.
+---
+---This will cause objects to appear bigger or smaller.
---
---The scaling will last until `lovr.draw` returns or the transformation is popped off the transformation stack.
---
+---
+---### NOTE:
+---Order matters when scaling, translating, and rotating the coordinate system.
+---
---@param x? number # The amount to scale on the x axis.
---@param y? number # The amount to scale on the y axis.
---@param z? number # The amount to scale on the z axis.
function lovr.graphics.scale(x, y, z) end
---
----Enables or disables alpha sampling. Alpha sampling is also known as alpha-to-coverage. When it is enabled, the alpha channel of a pixel is factored into how antialiasing is computed, so the edges of a transparent texture will be correctly antialiased.
+---Enables or disables alpha sampling.
+---
+---Alpha sampling is also known as alpha-to-coverage.
+---
+---When it is enabled, the alpha channel of a pixel is factored into how antialiasing is computed, so the edges of a transparent texture will be correctly antialiased.
+---
+---
+---### NOTE:
+---- Alpha sampling is disabled by default.
+---- This feature can be used for a simple transparency effect, pixels with an alpha of zero will
+--- have their depth value discarded, allowing things behind them to show through (normally you
+--- have to sort objects or write a shader for this).
---
---@param enabled boolean # Whether or not alpha sampling is enabled.
function lovr.graphics.setAlphaSampling(enabled) end
---
----Sets the background color used to clear the screen. Color components are from 0.0 to 1.0.
+---Sets the background color used to clear the screen.
+---
+---Color components are from 0.0 to 1.0.
+---
+---
+---### NOTE:
+---The default background color is `(0.0, 0.0, 0.0, 1.0)`.
---
---@overload fun(hex: number, a: number)
---@overload fun(color: table)
@@ -557,7 +979,13 @@ function lovr.graphics.setAlphaSampling(enabled) end
function lovr.graphics.setBackgroundColor(r, g, b, a) end
---
----Sets the blend mode. The blend mode controls how each pixel's color is blended with the previous pixel's color when drawn.
+---Sets the blend mode.
+---
+---The blend mode controls how each pixel's color is blended with the previous pixel's color when drawn.
+---
+---
+---### NOTE:
+---The default blend mode is `alpha` and `alphamultiply`.
---
---@overload fun()
---@param blend lovr.BlendMode # The blend mode.
@@ -565,13 +993,25 @@ function lovr.graphics.setBackgroundColor(r, g, b, a) end
function lovr.graphics.setBlendMode(blend, alphaBlend) end
---
----Sets or disables the active Canvas object. If there is an active Canvas, things will be rendered to the Textures attached to that Canvas instead of to the headset.
+---Sets or disables the active Canvas object.
+---
+---If there is an active Canvas, things will be rendered to the Textures attached to that Canvas instead of to the headset.
---
---@param canvas? lovr.Canvas # The new active Canvas object, or `nil` to just render to the headset.
function lovr.graphics.setCanvas(canvas) end
---
----Sets the color used for drawing objects. Color components are from 0.0 to 1.0. Every pixel drawn will be multiplied (i.e. tinted) by this color. This is a global setting, so it will affect all subsequent drawing operations.
+---Sets the color used for drawing objects.
+---
+---Color components are from 0.0 to 1.0.
+---
+---Every pixel drawn will be multiplied (i.e. tinted) by this color.
+---
+---This is a global setting, so it will affect all subsequent drawing operations.
+---
+---
+---### NOTE:
+---The default color is `(1.0, 1.0, 1.0, 1.0)`.
---
---@overload fun(hex: number, a: number)
---@overload fun(color: table)
@@ -582,7 +1022,15 @@ function lovr.graphics.setCanvas(canvas) end
function lovr.graphics.setColor(r, g, b, a) end
---
----Enables and disables individual color channels. When a color channel is enabled, it will be affected by drawing commands and clear commands.
+---Enables and disables individual color channels.
+---
+---When a color channel is enabled, it will be affected by drawing commands and clear commands.
+---
+---
+---### NOTE:
+---By default, all color channels are enabled.
+---
+---Disabling all of the color channels can be useful if you only want to write to the depth buffer or the stencil buffer.
---
---@param r boolean # Whether the red color channel should be enabled.
---@param g boolean # Whether the green color channel should be enabled.
@@ -591,20 +1039,60 @@ function lovr.graphics.setColor(r, g, b, a) end
function lovr.graphics.setColorMask(r, g, b, a) end
---
----Enables or disables culling. Culling is an optimization that avoids rendering the back face of polygons. This improves performance by reducing the number of polygons drawn, but requires that the vertices in triangles are specified in a consistent clockwise or counter clockwise order.
+---Enables or disables culling.
+---
+---Culling is an optimization that avoids rendering the back face of polygons.
+---
+---This improves performance by reducing the number of polygons drawn, but requires that the vertices in triangles are specified in a consistent clockwise or counter clockwise order.
+---
+---
+---### NOTE:
+---Culling is disabled by default.
---
---@param isEnabled boolean # Whether or not culling should be enabled.
function lovr.graphics.setCullingEnabled(isEnabled) end
---
----Sets the default filter mode for new Textures. This controls how textures are sampled when they are minified, magnified, or stretched.
+---Sets the default filter mode for new Textures.
+---
+---This controls how textures are sampled when they are minified, magnified, or stretched.
+---
+---
+---### NOTE:
+---The default filter is `trilinear`.
+---
+---The maximum supported anisotropy level can be queried using `lovr.graphics.getLimits`.
---
---@param mode lovr.FilterMode # The filter mode.
---@param anisotropy number # The level of anisotropy to use.
function lovr.graphics.setDefaultFilter(mode, anisotropy) end
---
----Sets the current depth test. The depth test controls how overlapping objects are rendered.
+---Sets the current depth test.
+---
+---The depth test controls how overlapping objects are rendered.
+---
+---
+---### NOTE:
+---The depth test is an advanced technique to control how 3D objects overlap each other when they are rendered.
+---
+---It works as follows:
+---
+---- Each pixel keeps track of its z value as well as its color.
+---- If `write` is enabled when something is drawn, then any pixels that are drawn will have their
+--- z values updated.
+---- Additionally, anything drawn will first compare the existing z value of a pixel with the new z
+--- value.
+---
+---The `compareMode` setting determines how this comparison is performed.
+---
+---If the
+--- comparison succeeds, the new pixel will overwrite the previous one, otherwise that pixel won't
+--- be rendered to.
+---
+---Smaller z values are closer to the camera.
+---
+---The default compare mode is `lequal`, which usually gives good results for normal 3D rendering.
---
---@param compareMode? lovr.CompareMode # The new depth test. Use `nil` to disable the depth test.
---@param write? boolean # Whether pixels will have their z value updated when rendered to.
@@ -619,19 +1107,49 @@ function lovr.graphics.setFont(font) end
---
---Sets the width of lines rendered using `lovr.graphics.line`.
---
+---
+---### NOTE:
+---The default line width is `1`.
+---
+---GPU driver support for line widths is poor.
+---
+---The actual width of lines may be different from what is set here.
+---
+---In particular, some graphics drivers only support a line width of `1`.
+---
+---Currently this function only supports integer values from 1 to 255.
+---
---@param width? number # The new line width, in pixels.
function lovr.graphics.setLineWidth(width) end
---
---Sets the width of drawn points, in pixels.
---
+---
+---### NOTE:
+---The default point size is `1.0`.
+---
---@param size? number # The new point size.
function lovr.graphics.setPointSize(size) end
---
----Sets the projection for a single view. 4 field of view angles can be used, similar to the field of view returned by `lovr.headset.getViewAngles`. Alternatively, a projection matrix can be used for other types of projections like orthographic, oblique, etc.
+---Sets the projection for a single view.
+---
+---4 field of view angles can be used, similar to the field of view returned by `lovr.headset.getViewAngles`.
+---
+---Alternatively, a projection matrix can be used for other types of projections like orthographic, oblique, etc.
+---
+---Two views are supported, one for each eye.
+---
+---When rendering to the headset, both projections are changed to match the ones used by the headset.
+---
+---
+---### NOTE:
+---Non-stereo rendering will only use the first view.
---
----Two views are supported, one for each eye. When rendering to the headset, both projections are changed to match the ones used by the headset.
+---The projection matrices are available as the `mat4 lovrProjections[2]` variable in shaders.
+---
+---The current projection matrix is available as `lovrProjection`.
---
---@overload fun(view: number, matrix: lovr.Mat4)
---@param view number # The index of the view to update.
@@ -649,7 +1167,19 @@ function lovr.graphics.setProjection(view, left, right, up, down) end
function lovr.graphics.setShader(shader) end
---
----Sets the stencil test. The stencil test lets you mask out pixels that meet certain criteria, based on the contents of the stencil buffer. The stencil buffer can be modified using `lovr.graphics.stencil`. After rendering to the stencil buffer, the stencil test can be set to control how subsequent drawing functions are masked by the stencil buffer.
+---Sets the stencil test.
+---
+---The stencil test lets you mask out pixels that meet certain criteria, based on the contents of the stencil buffer.
+---
+---The stencil buffer can be modified using `lovr.graphics.stencil`.
+---
+---After rendering to the stencil buffer, the stencil test can be set to control how subsequent drawing functions are masked by the stencil buffer.
+---
+---
+---### NOTE:
+---Stencil values are between 0 and 255.
+---
+---By default, the stencil test is disabled.
---
---@overload fun()
---@param compareMode lovr.CompareMode # The comparison method used to decide if a pixel should be visible, or nil if the stencil test is disabled.
@@ -657,9 +1187,23 @@ function lovr.graphics.setShader(shader) end
function lovr.graphics.setStencilTest(compareMode, compareValue) end
---
----Sets the pose for a single view. Objects rendered in this view will appear as though the camera is positioned using the given pose.
+---Sets the pose for a single view.
---
----Two views are supported, one for each eye. When rendering to the headset, both views are changed to match the estimated eye positions. These view poses are also available using `lovr.headset.getViewPose`.
+---Objects rendered in this view will appear as though the camera is positioned using the given pose.
+---
+---Two views are supported, one for each eye.
+---
+---When rendering to the headset, both views are changed to match the estimated eye positions.
+---
+---These view poses are also available using `lovr.headset.getViewPose`.
+---
+---
+---### NOTE:
+---Non-stereo rendering will only use the first view.
+---
+---The inverted view poses (view matrices) are available as the `mat4 lovrViews[2]` variable in shaders.
+---
+---The current view matrix is available as `lovrView`.
---
---@overload fun(view: number, matrix: lovr.Mat4, inverted: boolean)
---@param view number # The index of the view to update.
@@ -673,19 +1217,41 @@ function lovr.graphics.setStencilTest(compareMode, compareValue) end
function lovr.graphics.setViewPose(view, x, y, z, angle, ax, ay, az) end
---
----Sets the polygon winding. The winding direction determines which face of a triangle is the front face and which is the back face. This lets the graphics engine cull the back faces of polygons, improving performance. The default is counterclockwise.
+---Sets the polygon winding.
+---
+---The winding direction determines which face of a triangle is the front face and which is the back face.
+---
+---This lets the graphics engine cull the back faces of polygons, improving performance.
+---
+---The default is counterclockwise.
+---
+---
+---### NOTE:
+---Culling is initially disabled and must be enabled using `lovr.graphics.setCullingEnabled`.
+---
+---The default winding direction is counterclockwise.
---
---@param winding lovr.Winding # The new winding direction.
function lovr.graphics.setWinding(winding) end
---
----Enables or disables wireframe rendering. This is meant to be used as a debugging tool.
+---Enables or disables wireframe rendering.
+---
+---This is meant to be used as a debugging tool.
+---
+---
+---### NOTE:
+---Wireframe rendering is initially disabled.
+---
+---Wireframe rendering is only supported on desktop systems.
---
---@param wireframe boolean # Whether or not wireframe rendering should be enabled.
function lovr.graphics.setWireframe(wireframe) end
---
----Render a skybox from a texture. Two common kinds of skybox textures are supported: A 2D equirectangular texture with a spherical coordinates can be used, or a "cubemap" texture created from 6 images.
+---Render a skybox from a texture.
+---
+---Two common kinds of skybox textures are supported: A 2D equirectangular texture with a spherical coordinates can be used, or a "cubemap" texture created from 6 images.
---
---@param texture lovr.Texture # The texture to use.
function lovr.graphics.skybox(texture) end
@@ -707,6 +1273,10 @@ function lovr.graphics.sphere(x, y, z, radius, angle, ax, ay, az) end
---
---Renders to the stencil buffer using a function.
---
+---
+---### NOTE:
+---Stencil values are between 0 and 255.
+---
---@overload fun(callback: function, action: lovr.StencilAction, value: number, initial: number)
---@param callback function # The function that will be called to render to the stencil buffer.
---@param action? lovr.StencilAction # How to modify the stencil value of pixels that are rendered to.
@@ -717,18 +1287,46 @@ function lovr.graphics.stencil(callback, action, value, keep) end
---
---Starts a named timer on the GPU, which can be stopped using `lovr.graphics.tock`.
---
+---
+---### NOTE:
+---The timer can be stopped by calling `lovr.graphics.tock` using the same name.
+---
+---All drawing commands between the tick and the tock will be timed.
+---
+---It is not possible to nest calls to tick and tock.
+---
+---GPU timers are not supported on all systems.
+---
+---Check the `timers` feature using `lovr.graphics.getFeatures` to see if it is supported on the current system.
+---
---@param label string # The name of the timer.
function lovr.graphics.tick(label) end
---
---Stops a named timer on the GPU, previously started with `lovr.graphics.tick`.
---
+---
+---### NOTE:
+---All drawing commands between tick and tock will be timed.
+---
+---It is not possible to nest calls to tick and tock.
+---
+---The results are delayed, and might be `nil` for the first few frames.
+---
+---This function returns the most recent available timer value.
+---
+---GPU timers are not supported on all systems.
+---
+---Check the `timers` feature using `lovr.graphics.getFeatures` to see if it is supported on the current system.
+---
---@param label string # The name of the timer.
---@return number time # The number of seconds elapsed, or `nil` if the data isn't ready yet.
function lovr.graphics.tock(label) end
---
----Apply a transform to the coordinate system, changing its translation, rotation, and scale using a single function. A `mat4` can also be used.
+---Apply a transform to the coordinate system, changing its translation, rotation, and scale using a single function.
+---
+---A `mat4` can also be used.
---
---The transformation will last until `lovr.draw` returns or the transformation is popped off the transformation stack.
---
@@ -746,25 +1344,45 @@ function lovr.graphics.tock(label) end
function lovr.graphics.transform(x, y, z, sx, sy, sz, angle, ax, ay, az) end
---
----Translates the coordinate system in three dimensions. All graphics operations that use coordinates will behave as if they are offset by the translation value.
+---Translates the coordinate system in three dimensions.
+---
+---All graphics operations that use coordinates will behave as if they are offset by the translation value.
---
---The translation will last until `lovr.draw` returns or the transformation is popped off the transformation stack.
---
+---
+---### NOTE:
+---Order matters when scaling, translating, and rotating the coordinate system.
+---
---@param x? number # The amount to translate on the x axis.
---@param y? number # The amount to translate on the y axis.
---@param z? number # The amount to translate on the z axis.
function lovr.graphics.translate(x, y, z) end
---
----A Canvas is also known as a framebuffer or render-to-texture. It allows you to render to a texture instead of directly to the screen. This lets you postprocess or transform the results later before finally rendering them to the screen.
+---A Canvas is also known as a framebuffer or render-to-texture.
+---
+---It allows you to render to a texture instead of directly to the screen.
+---
+---This lets you postprocess or transform the results later before finally rendering them to the screen.
---
---After creating a Canvas, you can attach Textures to it using `Canvas:setTexture`.
---
+---
+---### NOTE:
+---Up to four textures can be attached to a Canvas and anything rendered to the Canvas will be broadcast to all attached Textures.
+---
+---If you want to do render different things to different textures, use the `multicanvas` shader flag when creating your shader and implement the `void colors` function instead of the usual `vec4 color` function.
+---
+---You can then assign different output colors to `lovrCanvas[0]`, `lovrCanvas[1]`, etc. instead of returning a single color. Each color written to the array will end up in the corresponding texture attached to the Canvas.
+---
---@class lovr.Canvas
local Canvas = {}
---
----Returns the depth buffer used by the Canvas as a Texture. If the Canvas was not created with a readable depth buffer (the `depth.readable` flag in `lovr.graphics.newCanvas`), then this function will return `nil`.
+---Returns the depth buffer used by the Canvas as a Texture.
+---
+---If the Canvas was not created with a readable depth buffer (the `depth.readable` flag in `lovr.graphics.newCanvas`), then this function will return `nil`.
---
---@return lovr.Texture texture # The depth Texture of the Canvas.
function Canvas:getDepthTexture() end
@@ -772,6 +1390,10 @@ function Canvas:getDepthTexture() end
---
---Returns the dimensions of the Canvas, its Textures, and its depth buffer.
---
+---
+---### NOTE:
+---The dimensions of a Canvas can not be changed after it is created.
+---
---@return number width # The width of the Canvas, in pixels.
---@return number height # The height of the Canvas, in pixels.
function Canvas:getDimensions() end
@@ -779,11 +1401,21 @@ function Canvas:getDimensions() end
---
---Returns the height of the Canvas, its Textures, and its depth buffer.
---
+---
+---### NOTE:
+---The height of a Canvas can not be changed after it is created.
+---
---@return number height # The height of the Canvas, in pixels.
function Canvas:getHeight() end
---
----Returns the number of multisample antialiasing samples to use when rendering to the Canvas. Increasing this number will make the contents of the Canvas appear more smooth at the cost of performance. It is common to use powers of 2 for this value.
+---Returns the number of multisample antialiasing samples to use when rendering to the Canvas. Increasing this number will make the contents of the Canvas appear more smooth at the cost of performance.
+---
+---It is common to use powers of 2 for this value.
+---
+---
+---### NOTE:
+---All textures attached to the Canvas must be created with this MSAA value.
---
---@return number samples # The number of MSAA samples.
function Canvas:getMSAA() end
@@ -791,16 +1423,26 @@ function Canvas:getMSAA() end
---
---Returns the set of Textures currently attached to the Canvas.
---
+---
+---### NOTE:
+---Up to 4 Textures can be attached at once.
+---
function Canvas:getTexture() end
---
---Returns the width of the Canvas, its Textures, and its depth buffer.
---
+---
+---### NOTE:
+---The width of a Canvas can not be changed after it is created.
+---
---@return number width # The width of the Canvas, in pixels.
function Canvas:getWidth() end
---
----Returns whether the Canvas was created with the `stereo` flag. Drawing something to a stereo Canvas will draw it to two viewports in the left and right half of the Canvas, using transform information from two different eyes.
+---Returns whether the Canvas was created with the `stereo` flag.
+---
+---Drawing something to a stereo Canvas will draw it to two viewports in the left and right half of the Canvas, using transform information from two different eyes.
---
---@return boolean stereo # Whether the Canvas is stereo.
function Canvas:isStereo() end
@@ -813,54 +1455,103 @@ function Canvas:isStereo() end
function Canvas:newImage(index) end
---
----Renders to the Canvas using a function. All graphics functions inside the callback will affect the Canvas contents instead of directly rendering to the headset. This can be used in `lovr.update`.
+---Renders to the Canvas using a function.
+---
+---All graphics functions inside the callback will affect the Canvas contents instead of directly rendering to the headset.
+---
+---This can be used in `lovr.update`.
+---
+---
+---### NOTE:
+---Make sure you clear the contents of the canvas before rendering by using `lovr.graphics.clear`. Otherwise there might be data in the canvas left over from a previous frame.
+---
+---Also note that the transform stack is not modified by this function.
+---
+---If you plan on modifying the transform stack inside your callback it may be a good idea to use `lovr.graphics.push` and `lovr.graphics.pop` so you can revert to the previous transform afterwards.
---
---@param callback function # The function to use to render to the Canvas.
function Canvas:renderTo(callback) end
---
----Attaches one or more Textures to the Canvas. When rendering to the Canvas, everything will be drawn to all attached Textures. You can attach different layers of an array, cubemap, or volume texture, and also attach different mipmap levels of Textures.
+---Attaches one or more Textures to the Canvas.
+---
+---When rendering to the Canvas, everything will be drawn to all attached Textures.
+---
+---You can attach different layers of an array, cubemap, or volume texture, and also attach different mipmap levels of Textures.
+---
+---
+---### NOTE:
+---There are some restrictions on how textures can be attached:
+---
+---- Up to 4 textures can be attached at once.
+---- Textures must have the same dimensions and multisample settings as the Canvas.
+---
+---To specify layers and mipmaps to attach, specify them after the Texture.
+---
+---You can also optionally wrap them in a table.
---
function Canvas:setTexture() end
---
----A Font is an object created from a TTF file. It can be used to render text with `lovr.graphics.print`.
+---A Font is an object created from a TTF file.
+---
+---It can be used to render text with `lovr.graphics.print`.
---
---@class lovr.Font
local Font = {}
---
----Returns the maximum distance that any glyph will extend above the Font's baseline. Units are generally in meters, see `Font:getPixelDensity`.
+---Returns the maximum distance that any glyph will extend above the Font's baseline.
+---
+---Units are generally in meters, see `Font:getPixelDensity`.
---
---@return number ascent # The ascent of the Font.
function Font:getAscent() end
---
----Returns the baseline of the Font. This is where the characters "rest on", relative to the y coordinate of the drawn text. Units are generally in meters, see `Font:setPixelDensity`.
+---Returns the baseline of the Font.
+---
+---This is where the characters "rest on", relative to the y coordinate of the drawn text.
+---
+---Units are generally in meters, see `Font:setPixelDensity`.
---
---@return number baseline # The baseline of the Font.
function Font:getBaseline() end
---
----Returns the maximum distance that any glyph will extend below the Font's baseline. Units are generally in meters, see `Font:getPixelDensity` for more information. Note that due to the coordinate system for fonts, this is a negative value.
+---Returns the maximum distance that any glyph will extend below the Font's baseline.
+---
+---Units are generally in meters, see `Font:getPixelDensity` for more information.
+---
+---Note that due to the coordinate system for fonts, this is a negative value.
---
---@return number descent # The descent of the Font.
function Font:getDescent() end
---
----Returns the height of a line of text. Units are in meters, see `Font:setPixelDensity`.
+---Returns the height of a line of text.
+---
+---Units are in meters, see `Font:setPixelDensity`.
---
---@return number height # The height of a rendered line of text.
function Font:getHeight() end
---
----Returns the current line height multiplier of the Font. The default is 1.0.
+---Returns the current line height multiplier of the Font.
+---
+---The default is 1.0.
---
---@return number lineHeight # The line height.
function Font:getLineHeight() end
---
----Returns the current pixel density for the Font. The default is 1.0. Normally, this is in pixels per meter. When rendering to a 2D texture, the units are pixels.
+---Returns the current pixel density for the Font.
+---
+---The default is 1.0.
+---
+---Normally, this is in pixels per meter.
+---
+---When rendering to a 2D texture, the units are pixels.
---
---@return number pixelDensity # The current pixel density.
function Font:getPixelDensity() end
@@ -874,6 +1565,11 @@ function Font:getRasterizer() end
---
---Returns the width and line count of a string when rendered using the font, taking into account an optional wrap limit.
---
+---
+---### NOTE:
+---To get the correct units returned, make sure the pixel density is set with
+--- `Font:setPixelDensity`.
+---
---@param text string # The text to get the width of.
---@param wrap? number # The width at which to wrap lines, or 0 for no wrap.
---@return number width # The maximum width of any line in the text.
@@ -881,32 +1577,52 @@ function Font:getRasterizer() end
function Font:getWidth(text, wrap) end
---
----Returns whether the Font has a set of glyphs. Any combination of strings and numbers (corresponding to character codes) can be specified. This function will return true if the Font is able to render *all* of the glyphs.
+---Returns whether the Font has a set of glyphs.
+---
+---Any combination of strings and numbers (corresponding to character codes) can be specified.
+---
+---This function will return true if the Font is able to render *all* of the glyphs.
+---
+---
+---### NOTE:
+---It is a good idea to use this function when you're rendering an unknown or user-supplied string to avoid utterly embarrassing crashes.
---
---@return boolean has # Whether the Font has the glyphs.
function Font:hasGlyphs() end
---
----Sets the line height of the Font, which controls how far lines apart lines are vertically separated. This value is a ratio and the default is 1.0.
+---Sets the line height of the Font, which controls how far lines apart lines are vertically separated.
+---
+---This value is a ratio and the default is 1.0.
---
---@param lineHeight number # The new line height.
function Font:setLineHeight(lineHeight) end
---
----Sets the pixel density for the Font. Normally, this is in pixels per meter. When rendering to a 2D texture, the units are pixels.
+---Sets the pixel density for the Font.
+---
+---Normally, this is in pixels per meter.
+---
+---When rendering to a 2D texture, the units are pixels.
---
---@overload fun(self: lovr.Font)
---@param pixelDensity number # The new pixel density.
function Font:setPixelDensity(pixelDensity) end
---
----A Material is an object used to control how objects appear, through coloring, texturing, and shading. The Material itself holds sets of colors, textures, and other parameters that are made available to Shaders.
+---A Material is an object used to control how objects appear, through coloring, texturing, and shading.
+---
+---The Material itself holds sets of colors, textures, and other parameters that are made available to Shaders.
---
---@class lovr.Material
local Material = {}
---
----Returns a color property for a Material. Different types of colors are supported for different lighting parameters. Colors default to `(1.0, 1.0, 1.0, 1.0)` and are gamma corrected.
+---Returns a color property for a Material.
+---
+---Different types of colors are supported for different lighting parameters.
+---
+---Colors default to `(1.0, 1.0, 1.0, 1.0)` and are gamma corrected.
---
---@param colorType? lovr.MaterialColor # The type of color to get.
---@return number r # The red component of the color.
@@ -916,14 +1632,20 @@ local Material = {}
function Material:getColor(colorType) end
---
----Returns a numeric property of a Material. Scalar properties default to 1.0.
+---Returns a numeric property of a Material.
+---
+---Scalar properties default to 1.0.
---
---@param scalarType lovr.MaterialScalar # The type of property to get.
---@return number x # The value of the property.
function Material:getScalar(scalarType) end
---
----Returns a texture for a Material. Several predefined `MaterialTexture`s are supported. Any texture that is `nil` will use a single white pixel as a fallback.
+---Returns a texture for a Material.
+---
+---Several predefined `MaterialTexture`s are supported.
+---
+---Any texture that is `nil` will use a single white pixel as a fallback.
---
---@param textureType? lovr.MaterialTexture # The type of texture to get.
---@return lovr.Texture texture # The texture that is set, or `nil` if no texture is set.
@@ -932,6 +1654,10 @@ function Material:getTexture(textureType) end
---
---Returns the transformation applied to texture coordinates of the Material.
---
+---
+---### NOTE:
+---Although texture coordinates will automatically be transformed by the Material's transform, the material transform is exposed as the `mat3 lovrMaterialTransform` uniform variable in shaders, allowing it to be used for other purposes.
+---
---@return number ox # The texture coordinate x offset.
---@return number oy # The texture coordinate y offset.
---@return number sx # The texture coordinate x scale.
@@ -940,7 +1666,11 @@ function Material:getTexture(textureType) end
function Material:getTransform() end
---
----Sets a color property for a Material. Different types of colors are supported for different lighting parameters. Colors default to `(1.0, 1.0, 1.0, 1.0)` and are gamma corrected.
+---Sets a color property for a Material.
+---
+---Different types of colors are supported for different lighting parameters.
+---
+---Colors default to `(1.0, 1.0, 1.0, 1.0)` and are gamma corrected.
---
---@overload fun(self: lovr.Material, r: number, g: number, b: number, a: number)
---@overload fun(self: lovr.Material, colorType: lovr.MaterialColor, hex: number, a: number)
@@ -953,14 +1683,20 @@ function Material:getTransform() end
function Material:setColor(colorType, r, g, b, a) end
---
----Sets a numeric property of a Material. Scalar properties default to 1.0.
+---Sets a numeric property of a Material.
+---
+---Scalar properties default to 1.0.
---
---@param scalarType lovr.MaterialScalar # The type of property to set.
---@param x number # The value of the property.
function Material:setScalar(scalarType, x) end
---
----Sets a texture for a Material. Several predefined `MaterialTexture`s are supported. Any texture that is `nil` will use a single white pixel as a fallback.
+---Sets a texture for a Material.
+---
+---Several predefined `MaterialTexture`s are supported.
+---
+---Any texture that is `nil` will use a single white pixel as a fallback.
---
---@overload fun(self: lovr.Material, texture: lovr.Texture)
---@param textureType? lovr.MaterialTexture # The type of texture to set.
@@ -968,7 +1704,13 @@ function Material:setScalar(scalarType, x) end
function Material:setTexture(textureType, texture) end
---
----Sets the transformation applied to texture coordinates of the Material. This lets you offset, scale, or rotate textures as they are applied to geometry.
+---Sets the transformation applied to texture coordinates of the Material.
+---
+---This lets you offset, scale, or rotate textures as they are applied to geometry.
+---
+---
+---### NOTE:
+---Although texture coordinates will automatically be transformed by the Material's transform, the material transform is exposed as the `mat3 lovrMaterialTransform` uniform variable in shaders, allowing it to be used for other purposes.
---
---@param ox number # The texture coordinate x offset.
---@param oy number # The texture coordinate y offset.
@@ -980,17 +1722,85 @@ function Material:setTransform(ox, oy, sx, sy, angle) end
---
---A Mesh is a low-level graphics object that stores and renders a list of vertices.
---
----Meshes are really flexible since you can pack pretty much whatever you want in them. This makes them great for rendering arbitrary geometry, but it also makes them kinda difficult to use since you have to place each vertex yourself.
+---Meshes are really flexible since you can pack pretty much whatever you want in them.
+---
+---This makes them great for rendering arbitrary geometry, but it also makes them kinda difficult to use since you have to place each vertex yourself.
+---
+---It's possible to batch geometry with Meshes too.
+---
+---Instead of drawing a shape 100 times, it's much faster to pack 100 copies of the shape into a Mesh and draw the Mesh once.
---
----It's possible to batch geometry with Meshes too. Instead of drawing a shape 100 times, it's much faster to pack 100 copies of the shape into a Mesh and draw the Mesh once. Even storing just one copy in the Mesh and drawing that 100 times is usually faster.
+---Even storing just one copy in the Mesh and drawing that 100 times is usually faster.
---
---Meshes are also a good choice if you have an object that changes its shape over time.
---
+---
+---### NOTE:
+---Each vertex in a Mesh can hold several pieces of data.
+---
+---For example, you might want a vertex to keep track of its position, color, and a weight.
+---
+---Each one of these pieces of information is called a vertex **attribute**.
+---
+---A vertex attribute must have a name, a type, and a size.
+---
+---Here's what the "position" attribute would look like as a Lua table:
+---
+--- { 'vPosition', 'float', 3 } -- 3 floats, one for x, y, and z
+---
+---Every vertex in a Mesh must have the same set of attributes.
+---
+---We call this set of attributes the **format** of the Mesh, and it's specified as a simple table of attributes.
+---
+---For example, we could represent the format described above as:
+---
+--- {
+--- { 'vPosition', 'float', 3 },
+--- { 'vColor', 'byte', 4 },
+--- { 'vWeight', 'int', 1 }
+--- }
+---
+---When creating a Mesh, you can give it any format you want, or use the default.
+---
+---The default Mesh format looks like this:
+---
+--- {
+--- { 'lovrPosition', 'float', 3 },
+--- { 'lovrNormal', 'float', 3 },
+--- { 'lovrTexCoord', 'float', 2 }
+--- }
+---
+---Great, so why do we go through the trouble of naming everything in our vertex and saying what type and size it is? The cool part is that we can access this data in a Shader.
+---
+---We can write a vertex Shader that has `in` variables for every vertex attribute in our Mesh:
+---
+--- in vec3 vPosition;
+--- in vec4 vColor;
+--- in int vWeight;
+---
+--- vec4 position(mat4 projection, mat4 transform, vec4 vertex) {
+--- // Here we can access the vPosition, vColor, and vWeight of each vertex in the Mesh!
+--- }
+---
+---Specifying custom vertex data is really powerful and is often used for lighting, animation, and more!
+---
+---For more on the different data types available for the attributes, see `AttributeType`.
+---
---@class lovr.Mesh
local Mesh = {}
---
----Attaches attributes from another Mesh onto this one. This can be used to share vertex data across multiple meshes without duplicating the data, and can also be used for instanced rendering by using the `divisor` parameter.
+---Attaches attributes from another Mesh onto this one.
+---
+---This can be used to share vertex data across multiple meshes without duplicating the data, and can also be used for instanced rendering by using the `divisor` parameter.
+---
+---
+---### NOTE:
+---The attribute divisor is a number used to control how the attribute data relates to instancing. If 0, then the attribute data is considered "per vertex", and each vertex will get the next element of the attribute's data.
+---
+---If the divisor 1 or more, then the attribute data is considered "per instance", and every N instances will get the next element of the attribute data.
+---
+---To prevent cycles, it is not possible to attach attributes onto a Mesh that already has attributes attached to a different Mesh.
---
---@overload fun(self: lovr.Mesh, mesh: lovr.Mesh, divisor: number, ...)
---@overload fun(self: lovr.Mesh, mesh: lovr.Mesh, divisor: number, attributes: table)
@@ -1028,7 +1838,9 @@ function Mesh:draw(x, y, z, scale, angle, ax, ay, az, instances) end
function Mesh:getDrawMode() end
---
----Retrieve the current draw range for the Mesh. The draw range is a subset of the vertices of the Mesh that will be drawn.
+---Retrieve the current draw range for the Mesh.
+---
+---The draw range is a subset of the vertices of the Mesh that will be drawn.
---
---@return number start # The index of the first vertex that will be drawn, or nil if no draw range is set.
---@return number count # The number of vertices that will be drawn, or nil if no draw range is set.
@@ -1041,7 +1853,11 @@ function Mesh:getDrawRange() end
function Mesh:getMaterial() end
---
----Gets the data for a single vertex in the Mesh. The set of data returned depends on the Mesh's vertex format. The default vertex format consists of 8 floating point numbers: the vertex position, the vertex normal, and the texture coordinates.
+---Gets the data for a single vertex in the Mesh.
+---
+---The set of data returned depends on the Mesh's vertex format.
+---
+---The default vertex format consists of 8 floating point numbers: the vertex position, the vertex normal, and the texture coordinates.
---
---@param index number # The index of the vertex to retrieve.
function Mesh:getVertex(index) end
@@ -1049,6 +1865,10 @@ function Mesh:getVertex(index) end
---
---Returns the components of a specific attribute of a single vertex in the Mesh.
---
+---
+---### NOTE:
+---Meshes without a custom format have the vertex position as their first attribute, the normal vector as the second attribute, and the texture coordinate as the third attribute.
+---
---@param index number # The index of the vertex to retrieve the attribute of.
---@param attribute number # The index of the attribute to retrieve the components of.
function Mesh:getVertexAttribute(index, attribute) end
@@ -1056,17 +1876,27 @@ function Mesh:getVertexAttribute(index, attribute) end
---
---Returns the maximum number of vertices the Mesh can hold.
---
+---
+---### NOTE:
+---The size can only be set when creating the Mesh, and cannot be changed afterwards.
+---
+---A subset of the Mesh's vertices can be rendered, see `Mesh:setDrawRange`.
+---
---@return number size # The number of vertices the Mesh can hold.
function Mesh:getVertexCount() end
---
----Get the format table of the Mesh's vertices. The format table describes the set of data that each vertex contains.
+---Get the format table of the Mesh's vertices.
+---
+---The format table describes the set of data that each vertex contains.
---
---@return table format # The table of vertex attributes. Each attribute is a table containing the name of the attribute, the `AttributeType`, and the number of components.
function Mesh:getVertexFormat() end
---
----Returns the current vertex map for the Mesh. The vertex map is a list of indices in the Mesh, allowing the reordering or reuse of vertices.
+---Returns the current vertex map for the Mesh.
+---
+---The vertex map is a list of indices in the Mesh, allowing the reordering or reuse of vertices.
---
---@overload fun(self: lovr.Mesh, t: table):table
---@overload fun(self: lovr.Mesh, blob: lovr.Blob)
@@ -1074,14 +1904,18 @@ function Mesh:getVertexFormat() end
function Mesh:getVertexMap() end
---
----Returns whether or not a vertex attribute is enabled. Disabled attributes won't be sent to shaders.
+---Returns whether or not a vertex attribute is enabled.
+---
+---Disabled attributes won't be sent to shaders.
---
---@param attribute string # The name of the attribute.
---@return boolean enabled # Whether or not the attribute is enabled when drawing the Mesh.
function Mesh:isAttributeEnabled(attribute) end
---
----Sets whether a vertex attribute is enabled. Disabled attributes won't be sent to shaders.
+---Sets whether a vertex attribute is enabled.
+---
+---Disabled attributes won't be sent to shaders.
---
---@param attribute string # The name of the attribute.
---@param enabled boolean # Whether or not the attribute is enabled when drawing the Mesh.
@@ -1094,7 +1928,9 @@ function Mesh:setAttributeEnabled(attribute, enabled) end
function Mesh:setDrawMode(mode) end
---
----Set the draw range for the Mesh. The draw range is a subset of the vertices of the Mesh that will be drawn.
+---Set the draw range for the Mesh.
+---
+---The draw range is a subset of the vertices of the Mesh that will be drawn.
---
---@overload fun(self: lovr.Mesh)
---@param start number # The first vertex that will be drawn.
@@ -1102,7 +1938,9 @@ function Mesh:setDrawMode(mode) end
function Mesh:setDrawRange(start, count) end
---
----Applies a Material to the Mesh. This will cause it to use the Material's properties whenever it is rendered.
+---Applies a Material to the Mesh.
+---
+---This will cause it to use the Material's properties whenever it is rendered.
---
---@param material lovr.Material # The Material to apply.
function Mesh:setMaterial(material) end
@@ -1110,18 +1948,28 @@ function Mesh:setMaterial(material) end
---
---Update a single vertex in the Mesh.
---
+---
+---### NOTE:
+---Any unspecified components will be set to 0.
+---
---@param index number # The index of the vertex to set.
function Mesh:setVertex(index) end
---
---Set the components of a specific attribute of a vertex in the Mesh.
---
+---
+---### NOTE:
+---Meshes without a custom format have the vertex position as their first attribute, the normal vector as the second attribute, and the texture coordinate as the third attribute.
+---
---@param index number # The index of the vertex to update.
---@param attribute number # The index of the attribute to update.
function Mesh:setVertexAttribute(index, attribute) end
---
----Sets the vertex map. The vertex map is a list of indices in the Mesh, allowing the reordering or reuse of vertices.
+---Sets the vertex map.
+---
+---The vertex map is a list of indices in the Mesh, allowing the reordering or reuse of vertices.
---
---Often, a vertex map is used to improve performance, since it usually requires less data to specify the index of a vertex than it does to specify all of the data for a vertex.
---
@@ -1132,6 +1980,10 @@ function Mesh:setVertexMap(map) end
---
---Updates multiple vertices in the Mesh.
---
+---
+---### NOTE:
+---The start index plus the number of vertices in the table should not exceed the maximum size of the Mesh.
+---
---@overload fun(self: lovr.Mesh, blob: lovr.Blob, start: number, count: number)
---@param vertices table # The new set of vertices.
---@param start? number # The index of the vertex to start replacing at.
@@ -1139,7 +1991,9 @@ function Mesh:setVertexMap(map) end
function Mesh:setVertices(vertices, start, count) end
---
----A Model is a drawable object loaded from a 3D file format. The supported 3D file formats are OBJ, glTF, and STL.
+---A Model is a drawable object loaded from a 3D file format.
+---
+---The supported 3D file formats are OBJ, glTF, and STL.
---
---@class lovr.Model
local Model = {}
@@ -1147,7 +2001,17 @@ local Model = {}
---
---Applies an animation to the current pose of the Model.
---
----The animation is evaluated at the specified timestamp, and mixed with the current pose of the Model using the alpha value. An alpha value of 1.0 will completely override the pose of the Model with the animation's pose.
+---The animation is evaluated at the specified timestamp, and mixed with the current pose of the Model using the alpha value.
+---
+---An alpha value of 1.0 will completely override the pose of the Model with the animation's pose.
+---
+---
+---### NOTE:
+---For animations to properly show up, use a Shader created with the `animated` flag set to `true`. See `lovr.graphics.newShader` for more.
+---
+---Animations are always mixed in with the current pose, and the pose only ever changes by calling `Model:animate` and `Model:pose`.
+---
+---To clear the pose of a Model to the default, use `Model:pose(nil)`.
---
---@overload fun(self: lovr.Model, index: number, time: number, alpha: number)
---@param name string # The name of an animation.
@@ -1241,6 +2105,12 @@ function Model:getNodeName(index) end
---
---Returns the pose of a single node in the Model in a given `CoordinateSpace`.
---
+---
+---### NOTE:
+---For skinned nodes to render correctly, use a Shader created with the `animated` flag set to `true`.
+---
+---See `lovr.graphics.newShader` for more.
+---
---@overload fun(self: lovr.Model, index: number, space: lovr.CoordinateSpace):number, number, number, number, number, number, number
---@param name string # The name of the node.
---@param space? lovr.CoordinateSpace # Whether the pose should be returned relative to the node's parent or relative to the root node of the Model.
@@ -1256,7 +2126,9 @@ function Model:getNodePose(name, space) end
---
---Returns 2 tables containing mesh data for the Model.
---
----The first table is a list of vertex positions and contains 3 numbers for the x, y, and z coordinate of each vertex. The second table is a list of triangles and contains 1-based indices into the first table representing the first, second, and third vertices that make up each triangle.
+---The first table is a list of vertex positions and contains 3 numbers for the x, y, and z coordinate of each vertex.
+---
+---The second table is a list of triangles and contains 1-based indices into the first table representing the first, second, and third vertices that make up each triangle.
---
---The vertex positions will be affected by node transforms.
---
@@ -1265,16 +2137,34 @@ function Model:getNodePose(name, space) end
function Model:getTriangles() end
---
----Returns whether the Model has any nodes associated with animated joints. This can be used to approximately determine whether an animated shader needs to be used with an arbitrary Model.
+---Returns whether the Model has any nodes associated with animated joints.
+---
+---This can be used to approximately determine whether an animated shader needs to be used with an arbitrary Model.
+---
+---
+---### NOTE:
+---A model can still be animated even if this function returns false, since node transforms can still be animated with keyframes without skinning.
+---
+---These types of animations don't need to use a Shader with the `animated = true` flag, though.
---
---@return boolean skeletal # Whether the Model has any nodes that use skeletal animation.
function Model:hasJoints() end
---
----Applies a pose to a single node of the Model. The input pose is assumed to be relative to the pose of the node's parent. This is useful for applying inverse kinematics (IK) to a chain of bones in a skeleton.
+---Applies a pose to a single node of the Model.
+---
+---The input pose is assumed to be relative to the pose of the node's parent.
+---
+---This is useful for applying inverse kinematics (IK) to a chain of bones in a skeleton.
---
---The alpha parameter can be used to mix between the node's current pose and the input pose.
---
+---
+---### NOTE:
+---For skinned nodes to render correctly, use a Shader created with the `animated` flag set to `true`.
+---
+---See `lovr.graphics.newShader` for more.
+---
---@overload fun(self: lovr.Model, index: number, x: number, y: number, z: number, angle: number, ax: number, ay: number, az: number, alpha: number)
---@overload fun(self: lovr.Model)
---@param name string # The name of the node.
@@ -1289,7 +2179,100 @@ function Model:hasJoints() end
function Model:pose(name, x, y, z, angle, ax, ay, az, alpha) end
---
----Shaders are GLSL programs that transform the way vertices and pixels show up on the screen. They can be used for lighting, postprocessing, particles, animation, and much more. You can use `lovr.graphics.setShader` to change the active Shader.
+---Shaders are GLSL programs that transform the way vertices and pixels show up on the screen. They can be used for lighting, postprocessing, particles, animation, and much more.
+---
+---You can use `lovr.graphics.setShader` to change the active Shader.
+---
+---
+---### NOTE:
+---GLSL version `330` is used on desktop systems, and `300 es` on WebGL/Android.
+---
+---The default vertex shader:
+---
+--- vec4 position(mat4 projection, mat4 transform, vec4 vertex) {
+--- return projection * transform * vertex;
+--- }
+---
+---The default fragment shader:
+---
+--- vec4 color(vec4 graphicsColor, sampler2D image, vec2 uv) {
+--- return graphicsColor * lovrDiffuseColor * lovrVertexColor * texture(image, uv);
+--- }
+---
+---Additionally, the following headers are prepended to the shader source, giving you convenient access to a default set of uniform variables and vertex attributes.
+---
+---Vertex shader header:
+---
+--- in vec3 lovrPosition; // The vertex position
+--- in vec3 lovrNormal; // The vertex normal vector
+--- in vec2 lovrTexCoord;
+--- in vec4 lovrVertexColor;
+--- in vec3 lovrTangent;
+--- in uvec4 lovrBones;
+--- in vec4 lovrBoneWeights;
+--- in uint lovrDrawID;
+--- out vec4 lovrGraphicsColor;
+--- uniform mat4 lovrModel;
+--- uniform mat4 lovrView;
+--- uniform mat4 lovrProjection;
+--- uniform mat4 lovrTransform; // Model-View matrix
+--- uniform mat3 lovrNormalMatrix; // Inverse-transpose of lovrModel
+--- uniform mat3 lovrMaterialTransform;
+--- uniform float lovrPointSize;
+--- uniform mat4 lovrPose[48];
+--- uniform int lovrViewportCount;
+--- uniform int lovrViewID;
+--- const mat4 lovrPoseMatrix; // Bone-weighted pose
+--- const int lovrInstanceID; // Current instance ID
+---
+---Fragment shader header:
+---
+--- in vec2 lovrTexCoord;
+--- in vec4 lovrVertexColor;
+--- in vec4 lovrGraphicsColor;
+--- out vec4 lovrCanvas[gl_MaxDrawBuffers];
+--- uniform float lovrMetalness;
+--- uniform float lovrRoughness;
+--- uniform vec4 lovrDiffuseColor;
+--- uniform vec4 lovrEmissiveColor;
+--- uniform sampler2D lovrDiffuseTexture;
+--- uniform sampler2D lovrEmissiveTexture;
+--- uniform sampler2D lovrMetalnessTexture;
+--- uniform sampler2D lovrRoughnessTexture;
+--- uniform sampler2D lovrOcclusionTexture;
+--- uniform sampler2D lovrNormalTexture;
+--- uniform samplerCube lovrEnvironmentTexture;
+--- uniform int lovrViewportCount;
+--- uniform int lovrViewID;
+---
+---### Compute Shaders
+---
+---Compute shaders can be created with `lovr.graphics.newComputeShader` and run with `lovr.graphics.compute`.
+---
+---Currently, compute shaders are written with raw GLSL.
+---
+---There is no default compute shader, instead the `void compute();` function must be implemented.
+---
+---You can use the `layout` qualifier to specify a local work group size:
+---
+--- layout(local_size_x = X, local_size_y = Y, local_size_z = Z) in;
+---
+---And the following built in variables can be used:
+---
+--- in uvec3 gl_NumWorkGroups; // The size passed to lovr.graphics.compute
+--- in uvec3 gl_WorkGroupSize; // The local work group size
+--- in uvec3 gl_WorkGroupID; // The current global work group
+--- in uvec3 gl_LocalInvocationID; // The current local work group
+--- in uvec3 gl_GlobalInvocationID; // A unique ID combining the global and local IDs
+--- in uint gl_LocalInvocationIndex; // A 1D index of the LocalInvocationID
+---
+---Compute shaders don't return anything but they can write data to `Texture`s or `ShaderBlock`s. To bind a texture in a way that can be written to a compute shader, declare the uniforms with a type of `image2D`, `imageCube`, etc. instead of the usual `sampler2D` or `samplerCube`.
+---
+---Once a texture is bound to an image uniform, you can use the `imageLoad` and `imageStore` GLSL functions to read and write pixels in the image.
+---
+---Variables in `ShaderBlock`s can be written to using assignment syntax.
+---
+---LÖVR handles synchronization of textures and shader blocks so there is no need to use manual memory barriers to synchronize writes to resources from compute shaders.
---
---@class lovr.Shader
local Shader = {}
@@ -1297,7 +2280,9 @@ local Shader = {}
---
---Returns the type of the Shader, which will be "graphics" or "compute".
---
----Graphics shaders are created with `lovr.graphics.newShader` and can be used for rendering with `lovr.graphics.setShader`. Compute shaders are created with `lovr.graphics.newComputeShader` and can be run using `lovr.graphics.compute`.
+---Graphics shaders are created with `lovr.graphics.newShader` and can be used for rendering with `lovr.graphics.setShader`.
+---
+---Compute shaders are created with `lovr.graphics.newComputeShader` and can be run using `lovr.graphics.compute`.
---
---@return lovr.ShaderType type # The type of the Shader.
function Shader:getType() end
@@ -1305,7 +2290,11 @@ function Shader:getType() end
---
---Returns whether a Shader has a block.
---
----A block is added to the Shader code at creation time using `ShaderBlock:getShaderCode`. The block name (not the namespace) is used to link up the ShaderBlock object to the Shader. This function can be used to check if a Shader was created with a block using the given name.
+---A block is added to the Shader code at creation time using `ShaderBlock:getShaderCode`.
+---
+---The block name (not the namespace) is used to link up the ShaderBlock object to the Shader.
+---
+---This function can be used to check if a Shader was created with a block using the given name.
---
---@param block string # The name of the block.
---@return boolean present # Whether the shader has the specified block.
@@ -1314,6 +2303,10 @@ function Shader:hasBlock(block) end
---
---Returns whether a Shader has a particular uniform variable.
---
+---
+---### NOTE:
+---If a uniform variable is defined but unused in the shader, the shader compiler will optimize it out and the uniform will not report itself as present.
+---
---@param uniform string # The name of the uniform variable.
---@return boolean present # Whether the shader has the specified uniform.
function Shader:hasUniform(uniform) end
@@ -1321,13 +2314,106 @@ function Shader:hasUniform(uniform) end
---
---Updates a uniform variable in the Shader.
---
+---
+---### NOTE:
+---The shader does not need to be active to update its uniforms.
+---
+---The following type combinations are supported:
+---
+---<table>
+--- <thead>
+--- <tr>
+--- <td>Uniform type</td>
+--- <td>LÖVR type</td>
+--- </tr>
+--- </thead>
+--- <tbody>
+--- <tr>
+--- <td>float</td>
+--- <td>number</td>
+--- </tr>
+--- <tr>
+--- <td>int</td>
+--- <td>number</td>
+--- </tr>
+--- <tr>
+--- <td>vec2</td>
+--- <td>{ x, y }</td>
+--- </tr>
+--- <tr>
+--- <td>vec3</td>
+--- <td>{ x, y, z } or vec3</td>
+--- </tr>
+--- <tr>
+--- <td>vec4</td>
+--- <td>{ x, y, z, w }</td>
+--- </tr>
+--- <tr>
+--- <td>ivec2</td>
+--- <td>{ x, y }</td>
+--- </tr>
+--- <tr>
+--- <td>ivec3</td>
+--- <td>{ x, y, z }</td>
+--- </tr>
+--- <tr>
+--- <td>ivec4</td>
+--- <td>{ x, y, z, w }</td>
+--- </tr>
+--- <tr>
+--- <td>mat2</td>
+--- <td>{ x, ... }</td>
+--- </tr>
+--- <tr>
+--- <td>mat3</td>
+--- <td>{ x, ... }</td>
+--- </tr>
+--- <tr>
+--- <td>mat4</td>
+--- <td>{ x, ... } or mat4</td>
+--- </tr>
+--- <tr>
+--- <td>sampler</td>
+--- <td>Texture</td>
+--- </tr>
+--- <tr>
+--- <td>image</td>
+--- <td>Texture</td>
+--- </tr>
+--- </tbody> </table>
+---
+---Uniform arrays can be wrapped in tables or passed as multiple arguments.
+---
+---Textures must match the type of sampler or image they are being sent to.
+---
+---The following sampler (and image) types are currently supported:
+---
+---- `sampler2D`
+---- `sampler3D`
+---- `samplerCube`
+---- `sampler2DArray`
+---
+---`Blob`s can be used to pass arbitrary binary data to Shader variables.
+---
---@param uniform string # The name of the uniform to update.
---@param value any # The new value of the uniform.
---@return boolean success # Whether the uniform exists and was updated.
function Shader:send(uniform, value) end
---
----Sends a ShaderBlock to a Shader. After the block is sent, you can update the data in the block without needing to resend the block. The block can be sent to multiple shaders and they will all see the same data from the block.
+---Sends a ShaderBlock to a Shader.
+---
+---After the block is sent, you can update the data in the block without needing to resend the block.
+---
+---The block can be sent to multiple shaders and they will all see the same data from the block.
+---
+---
+---### NOTE:
+---The Shader does not need to be active to send it a block.
+---
+---Make sure the ShaderBlock's variables line up with the block variables declared in the shader code, otherwise you'll get garbage data in the block.
+---
+---An easy way to do this is to use `ShaderBlock:getShaderCode` to get a GLSL snippet that is compatible with the block.
---
---@param name string # The name of the block to send to.
---@param block lovr.ShaderBlock # The ShaderBlock to associate with the specified block.
@@ -1335,7 +2421,11 @@ function Shader:send(uniform, value) end
function Shader:sendBlock(name, block, access) end
---
----Sends a Texture to a Shader for writing. This is meant to be used with compute shaders and only works with uniforms declared as `image2D`, `imageCube`, `image2DArray`, and `image3D`. The normal `Shader:send` function accepts Textures and should be used most of the time.
+---Sends a Texture to a Shader for writing.
+---
+---This is meant to be used with compute shaders and only works with uniforms declared as `image2D`, `imageCube`, `image2DArray`, and `image3D`.
+---
+---The normal `Shader:send` function accepts Textures and should be used most of the time.
---
---@overload fun(self: lovr.Shader, name: string, index: number, texture: lovr.Texture, slice: number, mipmap: number, access: lovr.UniformAccess)
---@param name string # The name of the image uniform.
@@ -1346,27 +2436,48 @@ function Shader:sendBlock(name, block, access) end
function Shader:sendImage(name, texture, slice, mipmap, access) end
---
----ShaderBlocks are objects that can hold large amounts of data and can be sent to Shaders. It is common to use "uniform" variables to send data to shaders, but uniforms are usually limited to a few kilobytes in size. ShaderBlocks are useful for a few reasons:
+---ShaderBlocks are objects that can hold large amounts of data and can be sent to Shaders.
+---
+---It is common to use "uniform" variables to send data to shaders, but uniforms are usually limited to a few kilobytes in size.
+---
+---ShaderBlocks are useful for a few reasons:
---
---- They can hold a lot more data.
---- Shaders can modify the data in them, which is really useful for compute shaders.
---- Setting the data in a ShaderBlock updates the data for all Shaders using the block, so you
--- don't need to go around setting the same uniforms in lots of different shaders.
---
----On systems that support compute shaders, ShaderBlocks can optionally be "writable". A writable ShaderBlock is a little bit slower than a non-writable one, but shaders can modify its contents and it can be much, much larger than a non-writable ShaderBlock.
+---On systems that support compute shaders, ShaderBlocks can optionally be "writable".
+---
+---A writable ShaderBlock is a little bit slower than a non-writable one, but shaders can modify its contents and it can be much, much larger than a non-writable ShaderBlock.
+---
+---
+---### NOTE:
+---- A Shader can use up to 8 ShaderBlocks.
+---- ShaderBlocks can not contain textures.
+---- Some systems have bugs with `vec3` variables in ShaderBlocks.
+---
+---If you run into strange bugs,
+--- try switching to a `vec4` for the variable.
---
---@class lovr.ShaderBlock
local ShaderBlock = {}
---
----Returns the byte offset of a variable in a ShaderBlock. This is useful if you want to manually send binary data to the ShaderBlock using a `Blob` in `ShaderBlock:send`.
+---Returns the byte offset of a variable in a ShaderBlock.
+---
+---This is useful if you want to manually send binary data to the ShaderBlock using a `Blob` in `ShaderBlock:send`.
---
---@param field string # The name of the variable to get the offset of.
---@return number offset # The byte offset of the variable.
function ShaderBlock:getOffset(field) end
---
----Before a ShaderBlock can be used in a Shader, the Shader has to have the block's variables defined in its source code. This can be a tedious process, so you can call this function to return a GLSL string that contains this definition. Roughly, it will look something like this:
+---Before a ShaderBlock can be used in a Shader, the Shader has to have the block's variables defined in its source code.
+---
+---This can be a tedious process, so you can call this function to return a GLSL string that contains this definition.
+---
+---Roughly, it will look something like this:
---
--- layout(std140) uniform <label> {
--- <type> <name>[<count>];
@@ -1392,6 +2503,12 @@ function ShaderBlock:getType() end
---
---Returns a variable in the ShaderBlock.
---
+---
+---### NOTE:
+---This function is really slow! Only read back values when you need to.
+---
+---Vectors and matrices will be returned as (flat) tables.
+---
---@param name string # The name of the variable to read.
---@return any value # The value of the variable.
function ShaderBlock:read(name) end
@@ -1399,13 +2516,25 @@ function ShaderBlock:read(name) end
---
---Updates a variable in the ShaderBlock.
---
+---
+---### NOTE:
+---For scalar or vector types, use tables of numbers or `vec3`s for each vector.
+---
+---For matrix types, use tables of numbers or `mat4` objects.
+---
+---`Blob`s can also be used to pass arbitrary binary data to individual variables.
+---
---@overload fun(self: lovr.ShaderBlock, blob: lovr.Blob, offset: number, extent: number):number
---@param variable string # The name of the variable to update.
---@param value any # The new value of the uniform.
function ShaderBlock:send(variable, value) end
---
----A Texture is an image that can be applied to `Material`s. The supported file formats are `.png`, `.jpg`, `.hdr`, `.dds`, `.ktx`, and `.astc`. DDS and ASTC are compressed formats, which are recommended because they're smaller and faster.
+---A Texture is an image that can be applied to `Material`s.
+---
+---The supported file formats are `.png`, `.jpg`, `.hdr`, `.dds`, `.ktx`, and `.astc`.
+---
+---DDS and ASTC are compressed formats, which are recommended because they're smaller and faster.
---
---@class lovr.Texture
local Texture = {}
@@ -1440,7 +2569,13 @@ function Texture:getDimensions(mipmap) end
function Texture:getFilter() end
---
----Returns the format of the Texture. This describes how many color channels are in the texture as well as the size of each one. The most common format used is `rgba`, which contains red, green, blue, and alpha color channels. See `TextureFormat` for all of the possible formats.
+---Returns the format of the Texture.
+---
+---This describes how many color channels are in the texture as well as the size of each one.
+---
+---The most common format used is `rgba`, which contains red, green, blue, and alpha color channels.
+---
+---See `TextureFormat` for all of the possible formats.
---
---@return lovr.TextureFormat format # The format of the Texture.
function Texture:getFormat() end
@@ -1489,7 +2624,11 @@ function Texture:getWrap() end
function Texture:replacePixels(image, x, y, slice, mipmap) end
---
----Sets the compare mode for a texture. This is only used for "shadow samplers", which are uniform variables in shaders with type `sampler2DShadow`. Sampling a shadow sampler uses a sort of virtual depth test, and the compare mode of the texture is used to control how the depth test is performed.
+---Sets the compare mode for a texture.
+---
+---This is only used for "shadow samplers", which are uniform variables in shaders with type `sampler2DShadow`.
+---
+---Sampling a shadow sampler uses a sort of virtual depth test, and the compare mode of the texture is used to control how the depth test is performed.
---
---@param compareMode? lovr.CompareMode # The new compare mode. Use `nil` to disable the compare mode.
function Texture:setCompareMode(compareMode) end
@@ -1497,12 +2636,22 @@ function Texture:setCompareMode(compareMode) end
---
---Sets the `FilterMode` used by the texture.
---
+---
+---### NOTE:
+---The default setting for new textures can be set with `lovr.graphics.setDefaultFilter`.
+---
+---The maximum supported anisotropy level can be queried using `lovr.graphics.getLimits`.
+---
---@param mode lovr.FilterMode # The filter mode.
---@param anisotropy number # The level of anisotropy to use.
function Texture:setFilter(mode, anisotropy) end
---
----Sets the wrap mode of a texture. The wrap mode controls how the texture is sampled when texture coordinates lie outside the usual 0 - 1 range. The default for both directions is `repeat`.
+---Sets the wrap mode of a texture.
+---
+---The wrap mode controls how the texture is sampled when texture coordinates lie outside the usual 0 - 1 range.
+---
+---The default for both directions is `repeat`.
---
---@param horizontal lovr.WrapMode # How the texture should wrap horizontally.
---@param vertical? lovr.WrapMode # How the texture should wrap vertically.
@@ -1526,7 +2675,11 @@ function Texture:setWrap(horizontal, vertical) end
---| '"closed"'
---
----Here are the different data types available for vertex attributes in a Mesh. The ones that have a smaller range take up less memory, which improves performance a bit. The "u" stands for "unsigned", which means it can't hold negative values but instead has a larger positive range.
+---Here are the different data types available for vertex attributes in a Mesh.
+---
+---The ones that have a smaller range take up less memory, which improves performance a bit.
+---
+---The "u" stands for "unsigned", which means it can't hold negative values but instead has a larger positive range.
---
---@alias lovr.AttributeType
---
@@ -1561,13 +2714,21 @@ function Texture:setWrap(horizontal, vertical) end
---
---Different ways the alpha channel of pixels affects blending.
---
+---
+---### NOTE:
+---The premultiplied mode should be used if pixels being drawn have already been blended, or "pre-multiplied", by the alpha channel.
+---
+---This happens when rendering a framebuffer that contains pixels with transparent alpha values, since the stored color values have already been faded by alpha and don't need to be faded a second time with the alphamultiply blend mode.
+---
---@alias lovr.BlendAlphaMode
---
---Color channel values are multiplied by the alpha channel during blending.
---
---| '"alphamultiply"'
---
----Color channels are not multiplied by the alpha channel. This should be used if the pixels being drawn have already been blended, or "pre-multiplied", by the alpha channel.
+---Color channels are not multiplied by the alpha channel.
+---
+---This should be used if the pixels being drawn have already been blended, or "pre-multiplied", by the alpha channel.
---
---| '"premultiplied"'
@@ -1639,7 +2800,13 @@ function Texture:setWrap(horizontal, vertical) end
---| '"stream"'
---
----The method used to compare z values when deciding how to overlap rendered objects. This is called the "depth test", and it happens on a pixel-by-pixel basis every time new objects are drawn. If the depth test "passes" for a pixel, then the pixel color will be replaced by the new color and the depth value in the depth buffer will be updated. Otherwise, the pixel will not be changed and the depth value will not be updated.
+---The method used to compare z values when deciding how to overlap rendered objects.
+---
+---This is called the "depth test", and it happens on a pixel-by-pixel basis every time new objects are drawn.
+---
+---If the depth test "passes" for a pixel, then the pixel color will be replaced by the new color and the depth value in the depth buffer will be updated.
+---
+---Otherwise, the pixel will not be changed and the depth value will not be updated.
---
---@alias lovr.CompareMode
---
@@ -1681,7 +2848,11 @@ function Texture:setWrap(horizontal, vertical) end
---| '"global"'
---
----The following shaders are built in to LÖVR, and can be used as an argument to `lovr.graphics.newShader` instead of providing raw GLSL shader code. The shaders can be further customized by using the `flags` argument. If you pass in `nil` to `lovr.graphics.setShader`, LÖVR will automatically pick a DefaultShader to use based on whatever is being drawn.
+---The following shaders are built in to LÖVR, and can be used as an argument to `lovr.graphics.newShader` instead of providing raw GLSL shader code.
+---
+---The shaders can be further customized by using the `flags` argument.
+---
+---If you pass in `nil` to `lovr.graphics.setShader`, LÖVR will automatically pick a DefaultShader to use based on whatever is being drawn.
---
---@alias lovr.DefaultShader
---
@@ -1710,7 +2881,9 @@ function Texture:setWrap(horizontal, vertical) end
---| '"fill"'
---
----Meshes are lists of arbitrary vertices. These vertices can be connected in different ways, leading to different shapes like lines and triangles.
+---Meshes are lists of arbitrary vertices.
+---
+---These vertices can be connected in different ways, leading to different shapes like lines and triangles.
---
---@alias lovr.DrawMode
---
@@ -1730,7 +2903,9 @@ function Texture:setWrap(horizontal, vertical) end
---
---| '"lineloop"'
---
----The first three vertices define a triangle. Each vertex after that creates a triangle using the new vertex and last two vertices.
+---The first three vertices define a triangle.
+---
+---Each vertex after that creates a triangle using the new vertex and last two vertices.
---
---| '"strip"'
---
@@ -1738,7 +2913,9 @@ function Texture:setWrap(horizontal, vertical) end
---
---| '"triangles"'
---
----Draws a set of triangles. Each one shares the first vertex as a common point, leading to a fan-like shape.
+---Draws a set of triangles.
+---
+---Each one shares the first vertex as a common point, leading to a fan-like shape.
---
---| '"fan"'
@@ -1756,11 +2933,17 @@ function Texture:setWrap(horizontal, vertical) end
---| '"line"'
---
----The method used to downsample (or upsample) a texture. "nearest" can be used for a pixelated effect, whereas "linear" leads to more smooth results. Nearest is slightly faster than linear.
+---The method used to downsample (or upsample) a texture.
+---
+---"nearest" can be used for a pixelated effect, whereas "linear" leads to more smooth results.
+---
+---Nearest is slightly faster than linear.
---
---@alias lovr.FilterMode
---
----Fast nearest-neighbor sampling. Leads to a pixelated style.
+---Fast nearest-neighbor sampling.
+---
+---Leads to a pixelated style.
---
---| '"nearest"'
---
@@ -1849,7 +3032,9 @@ function Texture:setWrap(horizontal, vertical) end
---| '"environment"'
---
----Meshes can have a usage hint, describing how they are planning on being updated. Setting the usage hint allows the graphics driver optimize how it handles the data in the Mesh.
+---Meshes can have a usage hint, describing how they are planning on being updated.
+---
+---Setting the usage hint allows the graphics driver optimize how it handles the data in the Mesh.
---
---@alias lovr.MeshUsage
---
@@ -1866,7 +3051,11 @@ function Texture:setWrap(horizontal, vertical) end
---| '"stream"'
---
----Shaders can be used for either rendering operations or generic compute tasks. Graphics shaders are created with `lovr.graphics.newShader` and compute shaders are created with `lovr.graphics.newComputeShader`. `Shader:getType` can be used on an existing Shader to figure out what type it is.
+---Shaders can be used for either rendering operations or generic compute tasks.
+---
+---Graphics shaders are created with `lovr.graphics.newShader` and compute shaders are created with `lovr.graphics.newComputeShader`.
+---
+---`Shader:getType` can be used on an existing Shader to figure out what type it is.
---
---@alias lovr.ShaderType
---
@@ -1908,7 +3097,9 @@ function Texture:setWrap(horizontal, vertical) end
---| '"invert"'
---
----Textures can store their pixels in different formats. The set of color channels and the number of bits stored for each channel can differ, allowing Textures to optimize their storage for certain kinds of image formats or rendering techniques.
+---Textures can store their pixels in different formats.
+---
+---The set of color channels and the number of bits stored for each channel can differ, allowing Textures to optimize their storage for certain kinds of image formats or rendering techniques.
---
---@alias lovr.TextureFormat
---
@@ -1994,7 +3185,9 @@ function Texture:setWrap(horizontal, vertical) end
---| '"volume"'
---
----When binding writable resources to shaders using `Shader:sendBlock` and `Shader:sendImage`, an access pattern can be specified as a hint that says whether you plan to read or write to the resource (or both). Sometimes, LÖVR or the GPU driver can use this hint to get better performance or avoid stalling.
+---When binding writable resources to shaders using `Shader:sendBlock` and `Shader:sendImage`, an access pattern can be specified as a hint that says whether you plan to read or write to the resource (or both).
+---
+---Sometimes, LÖVR or the GPU driver can use this hint to get better performance or avoid stalling.
---
---@alias lovr.UniformAccess
---
diff --git a/meta/3rd/lovr/library/lovr.headset.lua b/meta/3rd/lovr/library/lovr.headset.lua
index e45d3009..218b70b9 100644
--- a/meta/3rd/lovr/library/lovr.headset.lua
+++ b/meta/3rd/lovr/library/lovr.headset.lua
@@ -1,16 +1,34 @@
---@meta
---
----The `lovr.headset` module is where all the magical VR functionality is. With it, you can access connected VR hardware and get information about the available space the player has. Note that all units are reported in meters. Position `(0, 0, 0)` is the center of the play area.
+---The `lovr.headset` module is where all the magical VR functionality is.
+---
+---With it, you can access connected VR hardware and get information about the available space the player has.
+---
+---Note that all units are reported in meters.
+---
+---Position `(0, 0, 0)` is the center of the play area.
---
---@class lovr.headset
lovr.headset = {}
---
----Animates a device model to match its current input state. The buttons and joysticks on a controller will move as they're pressed/moved and hand models will move to match skeletal input.
+---Animates a device model to match its current input state.
+---
+---The buttons and joysticks on a controller will move as they're pressed/moved and hand models will move to match skeletal input.
---
---The model should have been created using `lovr.headset.newModel` with the `animated` flag set to `true`.
---
+---
+---### NOTE:
+---Currently this function is supported for OpenVR controller models and Oculus hand models.
+---
+---This function may animate using node-based animation or skeletal animation.
+---
+---`Model:hasJoints` can be used on a Model so you know if a Shader with the `animated` ShaderFlag needs to be used to render the results properly.
+---
+---It's possible to use models that weren't created with `lovr.headset.newModel` but they need to be set up carefully to have the same structure as the models provided by the headset SDK.
+---
---@param device? lovr.Device # The device to use for the animation data.
---@param model lovr.Model # The model to animate.
---@return boolean success # Whether the animation was applied successfully to the Model. If the Model was not compatible or animation data for the device was not available, this will be `false`.
@@ -26,7 +44,17 @@ function lovr.headset.animate(device, model) end
function lovr.headset.getAngularVelocity(device) end
---
----Get the current state of an analog axis on a device. Some axes are multidimensional, for example a 2D touchpad or thumbstick with x/y axes. For multidimensional axes, this function will return multiple values, one number for each axis. In these cases, it can be useful to use the `select` function built in to Lua to select a particular axis component.
+---Get the current state of an analog axis on a device.
+---
+---Some axes are multidimensional, for example a 2D touchpad or thumbstick with x/y axes.
+---
+---For multidimensional axes, this function will return multiple values, one number for each axis.
+---
+---In these cases, it can be useful to use the `select` function built in to Lua to select a particular axis component.
+---
+---
+---### NOTE:
+---The axis values will be between 0 and 1 for 1D axes, and between -1 and 1 for each component of a multidimensional axis.
---
---@param device lovr.Device # The device.
---@param axis lovr.DeviceAxis # The axis.
@@ -35,12 +63,20 @@ function lovr.headset.getAxis(device, axis) end
---
---Returns the depth of the play area, in meters.
---
+---
+---### NOTE:
+---This currently returns 0 on the Quest.
+---
---@return number depth # The depth of the play area, in meters.
function lovr.headset.getBoundsDepth() end
---
---Returns the size of the play area, in meters.
---
+---
+---### NOTE:
+---This currently returns 0 on the Quest.
+---
---@return number width # The width of the play area, in meters.
---@return number depth # The depth of the play area, in meters.
function lovr.headset.getBoundsDimensions() end
@@ -55,11 +91,23 @@ function lovr.headset.getBoundsGeometry(t) end
---
---Returns the width of the play area, in meters.
---
+---
+---### NOTE:
+---This currently returns 0 on the Quest.
+---
---@return number width # The width of the play area, in meters.
function lovr.headset.getBoundsWidth() end
---
----Returns the near and far clipping planes used to render to the headset. Objects closer than the near clipping plane or further than the far clipping plane will be clipped out of view.
+---Returns the near and far clipping planes used to render to the headset.
+---
+---Objects closer than the near clipping plane or further than the far clipping plane will be clipped out of view.
+---
+---
+---### NOTE:
+---The default near and far clipping planes are 0.1 meters and 100.0 meters.
+---
+---This is not currently supported by the `vrapi` headset driver.
---
---@return number near # The distance to the near clipping plane, in meters.
---@return number far # The distance to the far clipping plane, in meters.
@@ -85,7 +133,11 @@ function lovr.headset.getDisplayFrequency() end
function lovr.headset.getDisplayHeight() end
---
----Returns 2D triangle vertices that represent areas of the headset display that will never be seen by the user (due to the circular lenses). This area can be masked out by rendering it to the depth buffer or stencil buffer. Then, further drawing operations can skip rendering those pixels using the depth test (`lovr.graphics.setDepthTest`) or stencil test (`lovr.graphics.setStencilTest`), which improves performance.
+---Returns 2D triangle vertices that represent areas of the headset display that will never be seen by the user (due to the circular lenses).
+---
+---This area can be masked out by rendering it to the depth buffer or stencil buffer.
+---
+---Then, further drawing operations can skip rendering those pixels using the depth test (`lovr.graphics.setDepthTest`) or stencil test (`lovr.graphics.setStencilTest`), which improves performance.
---
---@return table points # A table of points. Each point is a table with two numbers between 0 and 1.
function lovr.headset.getDisplayMask() end
@@ -97,7 +149,9 @@ function lovr.headset.getDisplayMask() end
function lovr.headset.getDisplayWidth() end
---
----Returns the `HeadsetDriver` that is currently in use, optionally for a specific device. The order of headset drivers can be changed using `lovr.conf` to prefer or exclude specific VR APIs.
+---Returns the `HeadsetDriver` that is currently in use, optionally for a specific device.
+---
+---The order of headset drivers can be changed using `lovr.conf` to prefer or exclude specific VR APIs.
---
---@overload fun(device: lovr.Device):lovr.HeadsetDriver
---@return lovr.HeadsetDriver driver # The driver of the headset in use, e.g. "OpenVR".
@@ -106,21 +160,71 @@ function lovr.headset.getDriver() end
---
---Returns a table with all of the currently tracked hand devices.
---
+---
+---### NOTE:
+---The hand paths will *always* be either `hand/left` or `hand/right`.
+---
---@return table hands # The currently tracked hand devices.
function lovr.headset.getHands() end
---
---Returns a Texture that contains whatever is currently rendered to the headset.
---
----Sometimes this can be `nil` if the current headset driver doesn't have a mirror texture, which can happen if the driver renders directly to the display. Currently the `desktop`, `webxr`, and `vrapi` drivers do not have a mirror texture.
+---Sometimes this can be `nil` if the current headset driver doesn't have a mirror texture, which can happen if the driver renders directly to the display.
---
----It also isn't guaranteed that the same Texture will be returned by subsequent calls to this function. Currently, the `oculus` driver exhibits this behavior.
+---Currently the `desktop`, `webxr`, and `vrapi` drivers do not have a mirror texture.
+---
+---It also isn't guaranteed that the same Texture will be returned by subsequent calls to this function.
+---
+---Currently, the `oculus` driver exhibits this behavior.
---
---@return lovr.Texture mirror # The mirror texture.
function lovr.headset.getMirrorTexture() end
---
----Returns the name of the headset as a string. The exact string that is returned depends on the hardware and VR SDK that is currently in use.
+---Returns the name of the headset as a string.
+---
+---The exact string that is returned depends on the hardware and VR SDK that is currently in use.
+---
+---
+---### NOTE:
+---<table>
+--- <thead>
+--- <tr>
+--- <td>driver</td>
+--- <td>name</td>
+--- </tr>
+--- </thead>
+--- <tbody>
+--- <tr>
+--- <td>desktop</td>
+--- <td><code>Simulator</code></td>
+--- </tr>
+--- <tr>
+--- <td>openvr</td>
+--- <td>varies</td>
+--- </tr>
+--- <tr>
+--- <td>openxr</td>
+--- <td>varies</td>
+--- </tr>
+--- <tr>
+--- <td>vrapi</td>
+--- <td><code>Oculus Quest</code> or <code>Oculus Quest 2</code></td>
+--- </tr>
+--- <tr>
+--- <td>webxr</td>
+--- <td>always nil</td>
+--- </tr>
+--- <tr>
+--- <td>oculus</td>
+--- <td>varies</td>
+--- </tr>
+--- <tr>
+--- <td>pico</td>
+--- <td><code>Pico</code></td>
+--- </tr>
+--- </tbody> </table>
---
---@return string name # The name of the headset as a string.
function lovr.headset.getName() end
@@ -128,6 +232,10 @@ function lovr.headset.getName() end
---
---Returns the current orientation of a device, in angle/axis form.
---
+---
+---### NOTE:
+---If the device isn't tracked, all zeroes will be returned.
+---
---@param device? lovr.Device # The device to get the orientation of.
---@return number angle # The amount of rotation around the axis of rotation, in radians.
---@return number ax # The x component of the axis of rotation.
@@ -136,7 +244,9 @@ function lovr.headset.getName() end
function lovr.headset.getOrientation(device) end
---
----Returns the type of origin used for the tracking volume. The different types of origins are explained on the `HeadsetOrigin` page.
+---Returns the type of origin used for the tracking volume.
+---
+---The different types of origins are explained on the `HeadsetOrigin` page.
---
---@return lovr.HeadsetOrigin origin # The type of origin.
function lovr.headset.getOriginType() end
@@ -144,6 +254,12 @@ function lovr.headset.getOriginType() end
---
---Returns the current position and orientation of a device.
---
+---
+---### NOTE:
+---Units are in meters.
+---
+---If the device isn't tracked, all zeroes will be returned.
+---
---@param device? lovr.Device # The device to get the pose of.
---@return number x # The x position.
---@return number y # The y position.
@@ -157,6 +273,10 @@ function lovr.headset.getPose(device) end
---
---Returns the current position of a device, in meters, relative to the play area.
---
+---
+---### NOTE:
+---If the device isn't tracked, all zeroes will be returned.
+---
---@param device? lovr.Device # The device to get the position of.
---@return number x # The x position of the device.
---@return number y # The y position of the device.
@@ -164,7 +284,140 @@ function lovr.headset.getPose(device) end
function lovr.headset.getPosition(device) end
---
----Returns a list of joint poses tracked by a device. Currently, only hand devices are able to track joints.
+---Returns a list of joint poses tracked by a device.
+---
+---Currently, only hand devices are able to track joints.
+---
+---
+---### NOTE:
+---If the Device does not support tracking joints or the poses are unavailable, `nil` is returned.
+---
+---The joint orientation is similar to the graphics coordinate system: -Z is the forwards direction, pointing towards the fingertips.
+---
+---The +Y direction is "up", pointing out of the back of the hand.
+---
+---The +X direction is to the right, perpendicular to X and Z.
+---
+---Hand joints are returned in the following order:
+---
+---<table>
+--- <thead>
+--- <tr>
+--- <td colspan="2">Joint</td>
+--- <td>Index</td>
+--- </tr>
+--- </thead>
+--- <tbody>
+--- <tr>
+--- <td colspan="2">Palm</td>
+--- <td>1</td>
+--- </tr>
+--- <tr>
+--- <td colspan="2">Wrist</td>
+--- <td>2</td>
+--- </tr>
+--- <tr>
+--- <td rowspan="4">Thumb</td>
+--- <td>Metacarpal</td>
+--- <td>3</td>
+--- </tr>
+--- <tr>
+--- <td>Proximal</td>
+--- <td>4</td>
+--- </tr>
+--- <tr>
+--- <td>Distal</td>
+--- <td>5</td>
+--- </tr>
+--- <tr>
+--- <td>Tip</td>
+--- <td>6</td>
+--- </tr>
+--- <tr>
+--- <td rowspan="5">Index</td>
+--- <td>Metacarpal</td>
+--- <td>7</td>
+--- </tr>
+--- <tr>
+--- <td>Proximal</td>
+--- <td>8</td>
+--- </tr>
+--- <tr>
+--- <td>Intermediate</td>
+--- <td>9</td>
+--- </tr>
+--- <tr>
+--- <td>Distal</td>
+--- <td>10</td>
+--- </tr>
+--- <tr>
+--- <td>Tip</td>
+--- <td>11</td>
+--- </tr>
+--- <tr>
+--- <td rowspan="5">Middle</td>
+--- <td>Metacarpal</td>
+--- <td>12</td>
+--- </tr>
+--- <tr>
+--- <td>Proximal</td>
+--- <td>13</td>
+--- </tr>
+--- <tr>
+--- <td>Intermediate</td>
+--- <td>14</td>
+--- </tr>
+--- <tr>
+--- <td>Distal</td>
+--- <td>15</td>
+--- </tr>
+--- <tr>
+--- <td>Tip</td>
+--- <td>16</td>
+--- </tr>
+--- <tr>
+--- <td rowspan="5">Ring</td>
+--- <td>Metacarpal</td>
+--- <td>17</td>
+--- </tr>
+--- <tr>
+--- <td>Proximal</td>
+--- <td>18</td>
+--- </tr>
+--- <tr>
+--- <td>Intermediate</td>
+--- <td>19</td>
+--- </tr>
+--- <tr>
+--- <td>Distal</td>
+--- <td>20</td>
+--- </tr>
+--- <tr>
+--- <td>Tip</td>
+--- <td>21</td>
+--- </tr>
+--- <tr>
+--- <td rowspan="5">Pinky</td>
+--- <td>Metacarpal</td>
+--- <td>22</td>
+--- </tr>
+--- <tr>
+--- <td>Proximal</td>
+--- <td>23</td>
+--- </tr>
+--- <tr>
+--- <td>Intermediate</td>
+--- <td>24</td>
+--- </tr>
+--- <tr>
+--- <td>Distal</td>
+--- <td>25</td>
+--- </tr>
+--- <tr>
+--- <td>Tip</td>
+--- <td>26</td>
+--- </tr>
+--- </tbody> </table>
---
---@overload fun(device: lovr.Device, t: table):table
---@param device lovr.Device # The Device to query.
@@ -176,6 +429,10 @@ function lovr.headset.getSkeleton(device) end
---
---This can be used as a replacement for `lovr.timer.getTime` for timestamps that are used for rendering to get a smoother result that is synchronized with the display of the headset.
---
+---
+---### NOTE:
+---This has a different epoch than `lovr.timer.getTime`, so it is not guaranteed to be close to that value.
+---
---@return number time # The predicted display time, in seconds.
function lovr.headset.getTime() end
@@ -203,15 +460,21 @@ function lovr.headset.getVelocity(device) end
function lovr.headset.getViewAngles(view) end
---
----Returns the number of views used for rendering. Each view consists of a pose in space and a set of angle values that determine the field of view.
+---Returns the number of views used for rendering.
+---
+---Each view consists of a pose in space and a set of angle values that determine the field of view.
+---
+---This is usually 2 for stereo rendering configurations, but it can also be different.
---
----This is usually 2 for stereo rendering configurations, but it can also be different. For example, one way of doing foveated rendering uses 2 views for each eye -- one low quality view with a wider field of view, and a high quality view with a narrower field of view.
+---For example, one way of doing foveated rendering uses 2 views for each eye -- one low quality view with a wider field of view, and a high quality view with a narrower field of view.
---
---@return number count # The number of views.
function lovr.headset.getViewCount() end
---
----Returns the pose of one of the headset views. This info can be used to create view matrices or do other eye-dependent calculations.
+---Returns the pose of one of the headset views.
+---
+---This info can be used to create view matrices or do other eye-dependent calculations.
---
---If tracking data is unavailable for the view or the index is invalid, `nil` is returned.
---
@@ -244,6 +507,10 @@ function lovr.headset.isTouched(device, button) end
---
---Returns whether any active headset driver is currently returning pose information for a device.
---
+---
+---### NOTE:
+---If a device is tracked, it is guaranteed to return a valid pose until the next call to `lovr.headset.update`.
+---
---@param device? lovr.Device # The device to get the pose of.
---@return boolean tracked # Whether the device is currently tracked.
function lovr.headset.isTracked(device) end
@@ -251,6 +518,10 @@ function lovr.headset.isTracked(device) end
---
---Returns a new Model for the specified device.
---
+---
+---### NOTE:
+---This is only supported on the `openvr` and `vrapi` drivers right now.
+---
---@param device? lovr.Device # The device to load a model for.
---@param options? {animated: boolean} # Options for loading the model.
---@return lovr.Model model # The new Model, or `nil` if a model could not be loaded.
@@ -259,15 +530,33 @@ function lovr.headset.newModel(device, options) end
---
---Renders to each eye of the headset using a function.
---
----This function takes care of setting the appropriate graphics transformations to ensure that the scene is rendered as though it is being viewed through each eye of the player. It also takes care of setting the correct projection for the headset lenses.
+---This function takes care of setting the appropriate graphics transformations to ensure that the scene is rendered as though it is being viewed through each eye of the player.
+---
+---It also takes care of setting the correct projection for the headset lenses.
---
---If the headset module is enabled, this function is called automatically by `lovr.run` with `lovr.draw` as the callback.
---
+---
+---### NOTE:
+---When using the `pico` headset driver, headset rendering is asynchronous and the callback passed to `lovr.headset.renderTo` will not be called immediately.
+---
+---At the beginning of the callback, the display is cleared to the background color.
+---
+---The background color can be changed using `lovr.graphics.setBackgroundColor`.
+---
+---If the callback is `nil`, an empty frame cleared to current graphics background color will be submitted to the headset.
+---
---@param callback function # The function used to render. Any functions called will render to the headset instead of to the window.
function lovr.headset.renderTo(callback) end
---
----Sets the near and far clipping planes used to render to the headset. Objects closer than the near clipping plane or further than the far clipping plane will be clipped out of view.
+---Sets the near and far clipping planes used to render to the headset.
+---
+---Objects closer than the near clipping plane or further than the far clipping plane will be clipped out of view.
+---
+---
+---### NOTE:
+---The default clip distances are 0.1 and 100.0.
---
---@param near number # The distance to the near clipping plane, in meters.
---@param far number # The distance to the far clipping plane, in meters.
@@ -276,6 +565,16 @@ function lovr.headset.setClipDistance(near, far) end
---
---Causes the device to vibrate with a custom strength, duration, and frequency, if possible.
---
+---
+---### NOTE:
+---When using the `openvr` headset driver on an HTC Vive, the value for the `duration` currently must be less than .004 seconds.
+---
+---Call this function several frames in a row for stronger or prolonged vibration patterns.
+---
+---On the Oculus Quest, devices can only be vibrated once per frame.
+---
+---Any attempts after the first will return `false`.
+---
---@param device? lovr.Device # The device to vibrate.
---@param strength? number # The strength of the vibration (amplitude), between 0 and 1.
---@param duration? number # The duration of the vibration, in seconds.
@@ -286,6 +585,14 @@ function lovr.headset.vibrate(device, strength, duration, frequency) end
---
---Returns whether a button on a device was pressed this frame.
---
+---
+---### NOTE:
+---Some headset backends are not able to return pressed/released information.
+---
+---These drivers will always return false for `lovr.headset.wasPressed` and `lovr.headset.wasReleased`.
+---
+---Typically the internal `lovr.headset.update` function will update pressed/released status.
+---
---@param device lovr.Device # The device.
---@param button lovr.DeviceButton # The button to check.
---@return boolean pressed # Whether the button on the device was pressed this frame.
@@ -294,6 +601,14 @@ function lovr.headset.wasPressed(device, button) end
---
---Returns whether a button on a device was released this frame.
---
+---
+---### NOTE:
+---Some headset backends are not able to return pressed/released information.
+---
+---These drivers will always return false for `lovr.headset.wasPressed` and `lovr.headset.wasReleased`.
+---
+---Typically the internal `lovr.headset.update` function will update pressed/released status.
+---
---@param device lovr.Device # The device.
---@param button lovr.DeviceButton # The button to check.
---@return boolean released # Whether the button on the device was released this frame.
@@ -463,9 +778,17 @@ function lovr.headset.wasReleased(device, button) end
---| '"proximity"'
---
----These are all of the supported VR APIs that LÖVR can use to power the lovr.headset module. You can change the order of headset drivers using `lovr.conf` to prefer or exclude specific VR APIs.
+---These are all of the supported VR APIs that LÖVR can use to power the lovr.headset module.
+---
+---You can change the order of headset drivers using `lovr.conf` to prefer or exclude specific VR APIs.
+---
+---At startup, LÖVR searches through the list of drivers in order.
---
----At startup, LÖVR searches through the list of drivers in order. One headset driver will be used for rendering to the VR display, and all supported headset drivers will be used for device input. The way this works is that when poses or button input is requested, the input drivers are queried (in the order they appear in `conf.lua`) to see if any of them currently have data for the specified device. The first one that returns data will be used to provide the result. This allows projects to support multiple types of hardware devices.
+---One headset driver will be used for rendering to the VR display, and all supported headset drivers will be used for device input.
+---
+---The way this works is that when poses or button input is requested, the input drivers are queried (in the order they appear in `conf.lua`) to see if any of them currently have data for the specified device.
+---
+---The first one that returns data will be used to provide the result. This allows projects to support multiple types of hardware devices.
---
---@alias lovr.HeadsetDriver
---
@@ -498,7 +821,11 @@ function lovr.headset.wasReleased(device, button) end
---| '"webxr"'
---
----Represents the different types of origins for coordinate spaces. An origin of "floor" means that the origin is on the floor in the middle of a room-scale play area. An origin of "head" means that no positional tracking is available, and consequently the origin is always at the position of the headset.
+---Represents the different types of origins for coordinate spaces.
+---
+---An origin of "floor" means that the origin is on the floor in the middle of a room-scale play area.
+---
+---An origin of "head" means that no positional tracking is available, and consequently the origin is always at the position of the headset.
---
---@alias lovr.HeadsetOrigin
---
diff --git a/meta/3rd/lovr/library/lovr.lua b/meta/3rd/lovr/library/lovr.lua
index 00a8f4b7..83acdec7 100644
--- a/meta/3rd/lovr/library/lovr.lua
+++ b/meta/3rd/lovr/library/lovr.lua
@@ -15,14 +15,30 @@ lovr = {}
function lovr.getVersion() end
---
----This is not a real object, but describes the behavior shared by all objects. Think of it as the superclass of all LÖVR objects.
+---This is not a real object, but describes the behavior shared by all objects.
---
----In addition to the methods here, all objects have a `__tostring` metamethod that returns the name of the object's type. So to check if a LÖVR object is an instance of "Blob", you can do `tostring(object) == 'Blob'`.
+---Think of it as the superclass of all LÖVR objects.
+---
+---In addition to the methods here, all objects have a `__tostring` metamethod that returns the name of the object's type.
+---
+---So to check if a LÖVR object is an instance of "Blob", you can do `tostring(object) == 'Blob'`.
+---
+---
+---### NOTE:
+---Note that the functions here don't apply to any vector objects, see `Vectors`.
---
---@class lovr.Object
local Object = {}
---
----Immediately destroys Lua's reference to the object it's called on. After calling this function on an object, it is an error to do anything with the object from Lua (call methods on it, pass it to other functions, etc.). If nothing else is using the object, it will be destroyed immediately, which can be used to destroy something earlier than it would normally be garbage collected in order to reduce memory.
+---Immediately destroys Lua's reference to the object it's called on.
+---
+---After calling this function on an object, it is an error to do anything with the object from Lua (call methods on it, pass it to other functions, etc.).
+---
+---If nothing else is using the object, it will be destroyed immediately, which can be used to destroy something earlier than it would normally be garbage collected in order to reduce memory.
+---
+---
+---### NOTE:
+---The object may not be destroyed immediately if something else is referring to it (e.g. it is pushed to a Channel or exists in the payload of a pending event).
---
function Object:release() end
diff --git a/meta/3rd/lovr/library/lovr.math.lua b/meta/3rd/lovr/library/lovr.math.lua
index 9c47ec48..7cf348c6 100644
--- a/meta/3rd/lovr/library/lovr.math.lua
+++ b/meta/3rd/lovr/library/lovr.math.lua
@@ -46,7 +46,9 @@ function lovr.math.getRandomSeed() end
function lovr.math.linearToGamma(lr, lg, lb) end
---
----Creates a temporary 4D matrix. This function takes the same arguments as `Mat4:set`.
+---Creates a temporary 4D matrix.
+---
+---This function takes the same arguments as `Mat4:set`.
---
function lovr.math.mat4() end
@@ -62,12 +64,16 @@ function lovr.math.mat4() end
function lovr.math.newCurve(x, y, z) end
---
----Creates a new 4D matrix. This function takes the same arguments as `Mat4:set`.
+---Creates a new 4D matrix.
+---
+---This function takes the same arguments as `Mat4:set`.
---
function lovr.math.newMat4() end
---
----Creates a new quaternion. This function takes the same arguments as `Quat:set`.
+---Creates a new quaternion.
+---
+---This function takes the same arguments as `Quat:set`.
---
function lovr.math.newQuat() end
@@ -80,22 +86,30 @@ function lovr.math.newQuat() end
function lovr.math.newRandomGenerator() end
---
----Creates a new 2D vector. This function takes the same arguments as `Vec2:set`.
+---Creates a new 2D vector.
+---
+---This function takes the same arguments as `Vec2:set`.
---
function lovr.math.newVec2() end
---
----Creates a new 3D vector. This function takes the same arguments as `Vec3:set`.
+---Creates a new 3D vector.
+---
+---This function takes the same arguments as `Vec3:set`.
---
function lovr.math.newVec3() end
---
----Creates a new 4D vector. This function takes the same arguments as `Vec4:set`.
+---Creates a new 4D vector.
+---
+---This function takes the same arguments as `Vec4:set`.
---
function lovr.math.newVec4() end
---
----Returns a 1D, 2D, 3D, or 4D perlin noise value. The number will be between 0 and 1, and it will always be 0.5 when the inputs are integers.
+---Returns a 1D, 2D, 3D, or 4D perlin noise value.
+---
+---The number will be between 0 and 1, and it will always be 0.5 when the inputs are integers.
---
---@overload fun(x: number, y: number):number
---@overload fun(x: number, y: number, z: number):number
@@ -105,12 +119,20 @@ function lovr.math.newVec4() end
function lovr.math.noise(x) end
---
----Creates a temporary quaternion. This function takes the same arguments as `Quat:set`.
+---Creates a temporary quaternion.
+---
+---This function takes the same arguments as `Quat:set`.
---
function lovr.math.quat() end
---
----Returns a uniformly distributed pseudo-random number. This function has improved randomness over Lua's `math.random` and also guarantees that the sequence of random numbers will be the same on all platforms (given the same seed).
+---Returns a uniformly distributed pseudo-random number.
+---
+---This function has improved randomness over Lua's `math.random` and also guarantees that the sequence of random numbers will be the same on all platforms (given the same seed).
+---
+---
+---### NOTE:
+---You can set the random seed using `lovr.math.setRandomSeed`.
---
---@overload fun(high: number):number
---@overload fun(low: number, high: number):number
@@ -118,7 +140,9 @@ function lovr.math.quat() end
function lovr.math.random() end
---
----Returns a pseudo-random number from a normal distribution (a bell curve). You can control the center of the bell curve (the mean value) and the overall width (sigma, or standard deviation).
+---Returns a pseudo-random number from a normal distribution (a bell curve).
+---
+---You can control the center of the bell curve (the mean value) and the overall width (sigma, or standard deviation).
---
---@param sigma? number # The standard deviation of the distribution. This can be thought of how "wide" the range of numbers is or how much variability there is.
---@param mu? number # The average value returned.
@@ -126,30 +150,44 @@ function lovr.math.random() end
function lovr.math.randomNormal(sigma, mu) end
---
----Seed the random generator with a new seed. Each seed will cause `lovr.math.random` and `lovr.math.randomNormal` to produce a unique sequence of random numbers. This is done once automatically at startup by `lovr.run`.
+---Seed the random generator with a new seed.
+---
+---Each seed will cause `lovr.math.random` and `lovr.math.randomNormal` to produce a unique sequence of random numbers.
+---
+---This is done once automatically at startup by `lovr.run`.
---
---@param seed number # The new seed.
function lovr.math.setRandomSeed(seed) end
---
----Creates a temporary 2D vector. This function takes the same arguments as `Vec2:set`.
+---Creates a temporary 2D vector.
+---
+---This function takes the same arguments as `Vec2:set`.
---
function lovr.math.vec2() end
---
----Creates a temporary 3D vector. This function takes the same arguments as `Vec3:set`.
+---Creates a temporary 3D vector.
+---
+---This function takes the same arguments as `Vec3:set`.
---
function lovr.math.vec3() end
---
----Creates a temporary 4D vector. This function takes the same arguments as `Vec4:set`.
+---Creates a temporary 4D vector.
+---
+---This function takes the same arguments as `Vec4:set`.
---
function lovr.math.vec4() end
---
----A Curve is an object that represents a Bézier curve in three dimensions. Curves are defined by an arbitrary number of control points (note that the curve only passes through the first and last control point).
+---A Curve is an object that represents a Bézier curve in three dimensions.
---
----Once a Curve is created with `lovr.math.newCurve`, you can use `Curve:evaluate` to get a point on the curve or `Curve:render` to get a list of all of the points on the curve. These points can be passed directly to `lovr.graphics.points` or `lovr.graphics.line` to render the curve.
+---Curves are defined by an arbitrary number of control points (note that the curve only passes through the first and last control point).
+---
+---Once a Curve is created with `lovr.math.newCurve`, you can use `Curve:evaluate` to get a point on the curve or `Curve:render` to get a list of all of the points on the curve.
+---
+---These points can be passed directly to `lovr.graphics.points` or `lovr.graphics.line` to render the curve.
---
---Note that for longer or more complicated curves (like in a drawing application) it can be easier to store the path as several Curve objects.
---
@@ -159,6 +197,10 @@ local Curve = {}
---
---Inserts a new control point into the Curve at the specified index.
---
+---
+---### NOTE:
+---An error will be thrown if the index is less than one or more than the number of control points.
+---
---@param x number # The x coordinate of the control point.
---@param y number # The y coordinate of the control point.
---@param z number # The z coordinate of the control point.
@@ -166,7 +208,13 @@ local Curve = {}
function Curve:addPoint(x, y, z, index) end
---
----Returns a point on the Curve given a parameter `t` from 0 to 1. 0 will return the first control point, 1 will return the last point, .5 will return a point in the "middle" of the Curve, etc.
+---Returns a point on the Curve given a parameter `t` from 0 to 1.
+---
+---0 will return the first control point, 1 will return the last point, .5 will return a point in the "middle" of the Curve, etc.
+---
+---
+---### NOTE:
+---An error will be thrown if `t` is not between 0 and 1, or if the Curve has less than two points.
---
---@param t number # The parameter to evaluate the Curve at.
---@return number x # The x position of the point.
@@ -177,6 +225,10 @@ function Curve:evaluate(t) end
---
---Returns a control point of the Curve.
---
+---
+---### NOTE:
+---An error will be thrown if the index is less than one or more than the number of control points.
+---
---@param index number # The index to retrieve.
---@return number x # The x coordinate of the control point.
---@return number y # The y coordinate of the control point.
@@ -190,7 +242,13 @@ function Curve:getPoint(index) end
function Curve:getPointCount() end
---
----Returns a direction vector for the Curve given a parameter `t` from 0 to 1. 0 will return the direction at the first control point, 1 will return the direction at the last point, .5 will return the direction at the "middle" of the Curve, etc.
+---Returns a direction vector for the Curve given a parameter `t` from 0 to 1.
+---
+---0 will return the direction at the first control point, 1 will return the direction at the last point, .5 will return the direction at the "middle" of the Curve, etc.
+---
+---
+---### NOTE:
+---The direction vector returned by this function will have a length of one.
---
---@param t number # Where on the Curve to compute the direction.
---@return number x # The x position of the point.
@@ -201,11 +259,21 @@ function Curve:getTangent(t) end
---
---Removes a control point from the Curve.
---
+---
+---### NOTE:
+---An error will be thrown if the index is less than one or more than the number of control points.
+---
---@param index number # The index of the control point to remove.
function Curve:removePoint(index) end
---
----Returns a list of points on the Curve. The number of points can be specified to get a more or less detailed representation, and it is also possible to render a subsection of the Curve.
+---Returns a list of points on the Curve.
+---
+---The number of points can be specified to get a more or less detailed representation, and it is also possible to render a subsection of the Curve.
+---
+---
+---### NOTE:
+---This function will always return 2 points if the Curve is a line with only 2 control points.
---
---@param n? number # The number of points to use.
---@param t1? number # How far along the curve to start rendering.
@@ -216,6 +284,10 @@ function Curve:render(n, t1, t2) end
---
---Changes the position of a control point on the Curve.
---
+---
+---### NOTE:
+---An error will be thrown if the index is less than one or more than the number of control points.
+---
---@param index number # The index to modify.
---@param x number # The new x coordinate.
---@param y number # The new y coordinate.
@@ -225,6 +297,12 @@ function Curve:setPoint(index, x, y, z) end
---
---Returns a new Curve created by slicing the Curve at the specified start and end points.
---
+---
+---### NOTE:
+---The new Curve will have the same number of control points as the existing curve.
+---
+---An error will be thrown if t1 or t2 are not between 0 and 1, or if the Curve has less than two points.
+---
---@param t1 number # The starting point to slice at.
---@param t2 number # The ending point to slice at.
---@return lovr.Curve curve # A new Curve.
@@ -276,7 +354,15 @@ function Mat4:invert() end
function Mat4:lookAt(from, to, up) end
---
----Multiplies this matrix by another value. Multiplying by a matrix combines their two transforms together. Multiplying by a vector applies the transformation from the matrix to the vector and returns the vector.
+---Multiplies this matrix by another value.
+---
+---Multiplying by a matrix combines their two transforms together.
+---
+---Multiplying by a vector applies the transformation from the matrix to the vector and returns the vector.
+---
+---
+---### NOTE:
+---When multiplying by a vec4, the vector is treated as either a point if its w component is 1, or a direction vector if the w is 0 (the matrix translation won't be applied).
---
---@overload fun(self: lovr.Mat4, v3: lovr.Vec3):lovr.Vec3
---@overload fun(self: lovr.Mat4, v4: lovr.Vec4):lovr.Vec4
@@ -377,7 +463,11 @@ function Mat4:unpack(raw) end
local Quat = {}
---
----Conjugates the input quaternion in place, returning the input. If the quaternion is normalized, this is the same as inverting it. It negates the (x, y, z) components of the quaternion.
+---Conjugates the input quaternion in place, returning the input.
+---
+---If the quaternion is normalized, this is the same as inverting it.
+---
+---It negates the (x, y, z) components of the quaternion.
---
---@return lovr.Quat q # The original quaternion.
function Quat:conjugate() end
@@ -395,7 +485,11 @@ function Quat:direction() end
function Quat:length() end
---
----Multiplies this quaternion by another value. If the value is a quaternion, the rotations in the two quaternions are applied sequentially and the result is stored in the first quaternion. If the value is a vector, then the input vector is rotated by the quaternion and returned.
+---Multiplies this quaternion by another value.
+---
+---If the value is a quaternion, the rotations in the two quaternions are applied sequentially and the result is stored in the first quaternion.
+---
+---If the value is a vector, then the input vector is rotated by the quaternion and returned.
---
---@overload fun(self: lovr.Quat, v3: lovr.vec3):lovr.vec3
---@param r lovr.quat # A quaternion to combine with the original.
@@ -405,11 +499,19 @@ function Quat:mul(r) end
---
---Adjusts the values in the quaternion so that its length becomes 1.
---
+---
+---### NOTE:
+---A common source of bugs with quaternions is to forget to normalize them after performing a series of operations on them.
+---
+---Try normalizing a quaternion if some of the calculations aren't working quite right!
+---
---@return lovr.Quat q # The original quaternion.
function Quat:normalize() end
---
----Sets the components of the quaternion. There are lots of different ways to specify the new components, the summary is:
+---Sets the components of the quaternion.
+---
+---There are lots of different ways to specify the new components, the summary is:
---
---- Four numbers can be used to specify an angle/axis rotation, similar to other LÖVR functions.
---- Four numbers plus the fifth `raw` flag can be used to set the raw values of the quaternion.
@@ -436,7 +538,11 @@ function Quat:set(angle, ax, ay, az, raw) end
---
---Performs a spherical linear interpolation between this quaternion and another one, which can be used for smoothly animating between two rotations.
---
----The amount of interpolation is controlled by a parameter `t`. A `t` value of zero leaves the original quaternion unchanged, whereas a `t` of one sets the original quaternion exactly equal to the target. A value between `0` and `1` returns a rotation between the two based on the value.
+---The amount of interpolation is controlled by a parameter `t`.
+---
+---A `t` value of zero leaves the original quaternion unchanged, whereas a `t` of one sets the original quaternion exactly equal to the target.
+---
+---A value between `0` and `1` returns a rotation between the two based on the value.
---
---@param r lovr.Quat # The quaternion to slerp towards.
---@param t number # The lerping parameter.
@@ -462,12 +568,22 @@ local RandomGenerator = {}
---
---Returns the seed used to initialize the RandomGenerator.
---
+---
+---### NOTE:
+---Since the seed is a 64 bit integer, each 32 bits of the seed are returned separately to avoid precision issues.
+---
---@return number low # The lower 32 bits of the seed.
---@return number high # The upper 32 bits of the seed.
function RandomGenerator:getSeed() end
---
----Returns the current state of the RandomGenerator. This can be used with `RandomGenerator:setState` to reliably restore a previous state of the generator.
+---Returns the current state of the RandomGenerator.
+---
+---This can be used with `RandomGenerator:setState` to reliably restore a previous state of the generator.
+---
+---
+---### NOTE:
+---The seed represents the starting state of the RandomGenerator, whereas the state represents the current state of the generator.
---
---@return string state # The serialized state.
function RandomGenerator:getState() end
@@ -481,7 +597,9 @@ function RandomGenerator:getState() end
function RandomGenerator:random() end
---
----Returns a pseudo-random number from a normal distribution (a bell curve). You can control the center of the bell curve (the mean value) and the overall width (sigma, or standard deviation).
+---Returns a pseudo-random number from a normal distribution (a bell curve).
+---
+---You can control the center of the bell curve (the mean value) and the overall width (sigma, or standard deviation).
---
---@param sigma? number # The standard deviation of the distribution. This can be thought of how "wide" the range of numbers is or how much variability there is.
---@param mu? number # The average value returned.
@@ -489,7 +607,13 @@ function RandomGenerator:random() end
function RandomGenerator:randomNormal(sigma, mu) end
---
----Seed the RandomGenerator with a new seed. Each seed will cause the RandomGenerator to produce a unique sequence of random numbers.
+---Seed the RandomGenerator with a new seed.
+---
+---Each seed will cause the RandomGenerator to produce a unique sequence of random numbers.
+---
+---
+---### NOTE:
+---For precise 64 bit seeds, you should specify the lower and upper 32 bits of the seed separately. Otherwise, seeds larger than 2^53 will start to lose precision.
---
---@overload fun(self: lovr.RandomGenerator, low: number, high: number)
---@param seed number # The random seed.
@@ -498,6 +622,10 @@ function RandomGenerator:setSeed(seed) end
---
---Sets the state of the RandomGenerator, as previously obtained using `RandomGenerator:getState`. This can be used to reliably restore a previous state of the generator.
---
+---
+---### NOTE:
+---The seed represents the starting state of the RandomGenerator, whereas the state represents the current state of the generator.
+---
---@param state string # The serialized state.
function RandomGenerator:setState(state) end
@@ -534,6 +662,14 @@ function Vec2:div(u) end
---
---Returns the dot product between this vector and another one.
---
+---
+---### NOTE:
+---This is computed as:
+---
+--- dot = v.x * u.x + v.y * u.y
+---
+---The vectors are not normalized before computing the dot product.
+---
---@overload fun(self: lovr.Vec2, x: number, y: number):number
---@param u lovr.Vec2 # The vector to compute the dot product with.
---@return number dot # The dot product between `v` and `u`.
@@ -542,11 +678,19 @@ function Vec2:dot(u) end
---
---Returns the length of the vector.
---
+---
+---### NOTE:
+---The length is equivalent to this:
+---
+--- math.sqrt(v.x * v.x + v.y * v.y)
+---
---@return number length # The length of the vector.
function Vec2:length() end
---
----Performs a linear interpolation between this vector and another one, which can be used to smoothly animate between two vectors, based on a parameter value. A parameter value of `0` will leave the vector unchanged, a parameter value of `1` will set the vector to be equal to the input vector, and a value of `.5` will set the components to be halfway between the two vectors.
+---Performs a linear interpolation between this vector and another one, which can be used to smoothly animate between two vectors, based on a parameter value.
+---
+---A parameter value of `0` will leave the vector unchanged, a parameter value of `1` will set the vector to be equal to the input vector, and a value of `.5` will set the components to be halfway between the two vectors.
---
---@overload fun(self: lovr.Vec2, x: number, y: number):lovr.Vec2
---@return lovr.Vec2 v # The original vector, containing the new lerped values.
@@ -605,7 +749,13 @@ local Vec3 = {}
function Vec3:add(u) end
---
----Sets this vector to be equal to the cross product between this vector and another one. The new `v` will be perpendicular to both the old `v` and `u`.
+---Sets this vector to be equal to the cross product between this vector and another one.
+---
+---The new `v` will be perpendicular to both the old `v` and `u`.
+---
+---
+---### NOTE:
+---The vectors are not normalized before or after computing the cross product.
---
---@overload fun(self: lovr.Vec3, x: number, y: number, z: number):lovr.Vec3
---@param u lovr.Vec3 # The vector to compute the cross product with.
@@ -631,6 +781,14 @@ function Vec3:div(u) end
---
---Returns the dot product between this vector and another one.
---
+---
+---### NOTE:
+---This is computed as:
+---
+--- dot = v.x * u.x + v.y * u.y + v.z * u.z
+---
+---The vectors are not normalized before computing the dot product.
+---
---@overload fun(self: lovr.Vec3, x: number, y: number, z: number):number
---@param u lovr.Vec3 # The vector to compute the dot product with.
---@return number dot # The dot product between `v` and `u`.
@@ -639,11 +797,19 @@ function Vec3:dot(u) end
---
---Returns the length of the vector.
---
+---
+---### NOTE:
+---The length is equivalent to this:
+---
+--- math.sqrt(v.x * v.x + v.y * v.y + v.z * v.z)
+---
---@return number length # The length of the vector.
function Vec3:length() end
---
----Performs a linear interpolation between this vector and another one, which can be used to smoothly animate between two vectors, based on a parameter value. A parameter value of `0` will leave the vector unchanged, a parameter value of `1` will set the vector to be equal to the input vector, and a value of `.5` will set the components to be halfway between the two vectors.
+---Performs a linear interpolation between this vector and another one, which can be used to smoothly animate between two vectors, based on a parameter value.
+---
+---A parameter value of `0` will leave the vector unchanged, a parameter value of `1` will set the vector to be equal to the input vector, and a value of `.5` will set the components to be halfway between the two vectors.
---
---@overload fun(self: lovr.Vec3, x: number, y: number, z: number, t: number):lovr.Vec3
---@param u lovr.Vec3 # The vector to lerp towards.
@@ -725,6 +891,14 @@ function Vec4:div(u) end
---
---Returns the dot product between this vector and another one.
---
+---
+---### NOTE:
+---This is computed as:
+---
+--- dot = v.x * u.x + v.y * u.y + v.z * u.z + v.w * u.w
+---
+---The vectors are not normalized before computing the dot product.
+---
---@overload fun(self: lovr.Vec4, x: number, y: number, z: number, w: number):number
---@param u lovr.Vec4 # The vector to compute the dot product with.
---@return number dot # The dot product between `v` and `u`.
@@ -733,11 +907,19 @@ function Vec4:dot(u) end
---
---Returns the length of the vector.
---
+---
+---### NOTE:
+---The length is equivalent to this:
+---
+--- math.sqrt(v.x * v.x + v.y * v.y * v.z + v.z + v.w * v.w)
+---
---@return number length # The length of the vector.
function Vec4:length() end
---
----Performs a linear interpolation between this vector and another one, which can be used to smoothly animate between two vectors, based on a parameter value. A parameter value of `0` will leave the vector unchanged, a parameter value of `1` will set the vector to be equal to the input vector, and a value of `.5` will set the components to be halfway between the two vectors.
+---Performs a linear interpolation between this vector and another one, which can be used to smoothly animate between two vectors, based on a parameter value.
+---
+---A parameter value of `0` will leave the vector unchanged, a parameter value of `1` will set the vector to be equal to the input vector, and a value of `.5` will set the components to be halfway between the two vectors.
---
---@overload fun(self: lovr.Vec4, x: number, y: number, z: number, w: number, t: number):lovr.Vec4
---@param u lovr.Vec4 # The vector to lerp towards.
@@ -788,7 +970,102 @@ function Vec4:sub(u) end
function Vec4:unpack() end
---
----LÖVR has math objects for vectors, matrices, and quaternions, collectively called "vector objects". Vectors are useful because they can represent a multidimensional quantity (like a 3D position) using just a single value.
+---LÖVR has math objects for vectors, matrices, and quaternions, collectively called "vector objects".
+---
+---Vectors are useful because they can represent a multidimensional quantity (like a 3D position) using just a single value.
+---
+---
+---### NOTE:
+---Most LÖVR functions that accept positions, orientations, transforms, velocities, etc. also accept vector objects, so they can be used interchangeably with numbers:
+---
+--- function lovr.draw()
+--- -- position and size are vec3's, rotation is a quat
+--- lovr.graphics.box('fill', position, size, rotation)
+--- end
+---
+---### Temporary vs. Permanent
+---
+---Vectors can be created in two different ways: **permanent** and **temporary**.
+---
+---**Permanent** vectors behave like normal Lua values.
+---
+---They are individual objects that are garbage collected when no longer needed.
+---
+---They're created using the usual `lovr.math.new<Type>` syntax:
+---
+--- self.position = lovr.math.newVec3(x, y, z)
+---
+---**Temporary** vectors are created from a shared pool of vector objects.
+---
+---This makes them faster because they use temporary memory and do not need to be garbage collected.
+---
+---To make a temporary vector, leave off the `new` prefix:
+---
+--- local position = lovr.math.vec3(x, y, z)
+---
+---As a further shorthand, these vector constructors are placed on the global scope.
+---
+---If you prefer to keep the global scope clean, this can be configured using the `t.math.globals` flag in `lovr.conf`.
+---
+--- local position = vec3(x1, y1, z1) + vec3(x2, y2, z2)
+---
+---Temporary vectors, with all their speed, come with an important restriction: they can only be used during the frame in which they were created.
+---
+---Saving them into variables and using them later on will throw an error:
+---
+--- local position = vec3(1, 2, 3)
+---
+--- function lovr.update(dt)
+--- -- Reusing a temporary vector across frames will error:
+--- position:add(vec3(dt))
+--- end
+---
+---It's possible to overflow the temporary vector pool.
+---
+---If that happens, `lovr.math.drain` can be used to periodically drain the pool, invalidating any existing temporary vectors.
+---
+---### Metamethods
+---
+---Vectors have metamethods, allowing them to be used using the normal math operators like `+`, `-`, `*`, `/`, etc.
+---
+--- print(vec3(2, 4, 6) * .5 + vec3(10, 20, 30))
+---
+---These metamethods will create new temporary vectors.
+---
+---### Components and Swizzles
+---
+---The raw components of a vector can be accessed like normal fields:
+---
+--- print(vec3(1, 2, 3).z) --> 3
+--- print(mat4()[16]) --> 1
+---
+---Also, multiple fields can be accessed and combined into a new (temporary) vector, called swizzling:
+---
+--- local position = vec3(10, 5, 1)
+--- print(position.xy) --> vec2(10, 5)
+--- print(position.xyy) --> vec3(10, 5, 5)
+--- print(position.zyxz) --> vec4(1, 5, 10, 1)
+---
+---The following fields are supported for vectors:
+---
+---- `x`, `y`, `z`, `w`
+---- `r`, `g`, `b`, `a`
+---- `s`, `t`, `p`, `q`
+---
+---Quaternions support `x`, `y`, `z`, and `w`.
+---
+---Matrices use numbers for accessing individual components in "column-major" order.
+---
+---All fields can also be assigned to.
+---
+--- -- Swap the components of a 2D vector
+--- v.xy = v.yx
+---
+---The `unpack` function can be used (on any vector type) to access all of the individual components of a vector object.
+---
+---For quaternions you can choose whether you want to unpack the angle/axis representation or the raw quaternion components.
+---
+---Similarly, matrices support raw unpacking as well as decomposition into translation/scale/rotation values.
---
---@class lovr.Vectors
local Vectors = {}
diff --git a/meta/3rd/lovr/library/lovr.physics.lua b/meta/3rd/lovr/library/lovr.physics.lua
index 7fef948b..fa65009b 100644
--- a/meta/3rd/lovr/library/lovr.physics.lua
+++ b/meta/3rd/lovr/library/lovr.physics.lua
@@ -9,6 +9,12 @@ lovr.physics = {}
---
---Creates a new BallJoint.
---
+---
+---### NOTE:
+---A ball joint is like a ball and socket between the two colliders.
+---
+---It tries to keep the distance between the colliders and the anchor position the same, but does not constrain the angle between them.
+---
---@param colliderA lovr.Collider # The first collider to attach the Joint to.
---@param colliderB lovr.Collider # The second collider to attach the Joint to.
---@param x number # The x position of the joint anchor point, in world coordinates.
@@ -20,6 +26,10 @@ function lovr.physics.newBallJoint(colliderA, colliderB, x, y, z) end
---
---Creates a new BoxShape.
---
+---
+---### NOTE:
+---A Shape can be attached to a Collider using `Collider:addShape`.
+---
---@param width? number # The width of the box, in meters.
---@param height? number # The height of the box, in meters.
---@param depth? number # The depth of the box, in meters.
@@ -27,7 +37,13 @@ function lovr.physics.newBallJoint(colliderA, colliderB, x, y, z) end
function lovr.physics.newBoxShape(width, height, depth) end
---
----Creates a new CapsuleShape. Capsules are cylinders with hemispheres on each end.
+---Creates a new CapsuleShape.
+---
+---Capsules are cylinders with hemispheres on each end.
+---
+---
+---### NOTE:
+---A Shape can be attached to a Collider using `Collider:addShape`.
---
---@param radius? number # The radius of the capsule, in meters.
---@param length? number # The length of the capsule, not including the caps, in meters.
@@ -37,6 +53,10 @@ function lovr.physics.newCapsuleShape(radius, length) end
---
---Creates a new CylinderShape.
---
+---
+---### NOTE:
+---A Shape can be attached to a Collider using `Collider:addShape`.
+---
---@param radius? number # The radius of the cylinder, in meters.
---@param length? number # The length of the cylinder, in meters.
---@return lovr.CylinderShape cylinder # The new CylinderShape.
@@ -45,6 +65,14 @@ function lovr.physics.newCylinderShape(radius, length) end
---
---Creates a new DistanceJoint.
---
+---
+---### NOTE:
+---A distance joint tries to keep the two colliders a fixed distance apart.
+---
+---The distance is determined by the initial distance between the anchor points.
+---
+---The joint allows for rotation on the anchor points.
+---
---@param colliderA lovr.Collider # The first collider to attach the Joint to.
---@param colliderB lovr.Collider # The second collider to attach the Joint to.
---@param x1 number # The x position of the first anchor point, in world coordinates.
@@ -59,6 +87,10 @@ function lovr.physics.newDistanceJoint(colliderA, colliderB, x1, y1, z1, x2, y2,
---
---Creates a new HingeJoint.
---
+---
+---### NOTE:
+---A hinge joint constrains two colliders to allow rotation only around the hinge's axis.
+---
---@param colliderA lovr.Collider # The first collider to attach the Joint to.
---@param colliderB lovr.Collider # The second collider to attach the Joint to.
---@param x number # The x position of the hinge anchor, in world coordinates.
@@ -73,6 +105,10 @@ function lovr.physics.newHingeJoint(colliderA, colliderB, x, y, z, ax, ay, az) e
---
---Creates a new SliderJoint.
---
+---
+---### NOTE:
+---A slider joint constrains two colliders to only allow movement along the slider's axis.
+---
---@param colliderA lovr.Collider # The first collider to attach the Joint to.
---@param colliderB lovr.Collider # The second collider to attach the Joint to.
---@param ax number # The x component of the slider axis.
@@ -84,6 +120,10 @@ function lovr.physics.newSliderJoint(colliderA, colliderB, ax, ay, az) end
---
---Creates a new SphereShape.
---
+---
+---### NOTE:
+---A Shape can be attached to a Collider using `Collider:addShape`.
+---
---@param radius? number # The radius of the sphere, in meters.
---@return lovr.SphereShape sphere # The new SphereShape.
function lovr.physics.newSphereShape(radius) end
@@ -91,6 +131,10 @@ function lovr.physics.newSphereShape(radius) end
---
---Creates a new physics World, which tracks the overall physics simulation, holds collider objects, and resolves collisions between them.
---
+---
+---### NOTE:
+---A World must be updated with `World:update` in `lovr.update` for the physics simulation to advance.
+---
---@param xg? number # The x component of the gravity force.
---@param yg? number # The y component of the gravity force.
---@param zg? number # The z component of the gravity force.
@@ -100,13 +144,19 @@ function lovr.physics.newSphereShape(radius) end
function lovr.physics.newWorld(xg, yg, zg, allowSleep, tags) end
---
----A BallJoint is a type of `Joint` that acts like a ball and socket between two colliders. It allows the colliders to rotate freely around an anchor point, but does not allow the colliders' distance from the anchor point to change.
+---A BallJoint is a type of `Joint` that acts like a ball and socket between two colliders.
+---
+---It allows the colliders to rotate freely around an anchor point, but does not allow the colliders' distance from the anchor point to change.
---
---@class lovr.BallJoint
local BallJoint = {}
---
----Returns the anchor points of the BallJoint, in world coordinates. The first point is the anchor on the first collider, and the second point is on the second collider. The joint tries to keep these points the same, but they may be different if the joint is forced apart by some other means.
+---Returns the anchor points of the BallJoint, in world coordinates.
+---
+---The first point is the anchor on the first collider, and the second point is on the second collider.
+---
+---The joint tries to keep these points the same, but they may be different if the joint is forced apart by some other means.
---
---@return number x1 # The x coordinate of the first anchor point, in world coordinates.
---@return number y1 # The y coordinate of the first anchor point, in world coordinates.
@@ -117,13 +167,17 @@ local BallJoint = {}
function BallJoint:getAnchors() end
---
----Returns the response time of the joint. See `World:setResponseTime` for more info.
+---Returns the response time of the joint.
+---
+---See `World:setResponseTime` for more info.
---
---@return number responseTime # The response time setting for the joint.
function BallJoint:getResponseTime() end
---
----Returns the tightness of the joint. See `World:setTightness` for how this affects the joint.
+---Returns the tightness of the joint.
+---
+---See `World:setTightness` for how this affects the joint.
---
---@return number tightness # The tightness of the joint.
function BallJoint:getTightness() end
@@ -137,13 +191,17 @@ function BallJoint:getTightness() end
function BallJoint:setAnchor(x, y, z) end
---
----Sets the response time of the joint. See `World:setResponseTime` for more info.
+---Sets the response time of the joint.
+---
+---See `World:setResponseTime` for more info.
---
---@param responseTime number # The new response time setting for the joint.
function BallJoint:setResponseTime(responseTime) end
---
----Sets the tightness of the joint. See `World:setTightness` for how this affects the joint.
+---Sets the tightness of the joint.
+---
+---See `World:setTightness` for how this affects the joint.
---
---@param tightness number # The tightness of the joint.
function BallJoint:setTightness(tightness) end
@@ -201,13 +259,17 @@ function CapsuleShape:setLength(length) end
function CapsuleShape:setRadius(radius) end
---
----Colliders are objects that represent a single rigid body in a physics simulation. They can have forces applied to them and collide with other colliders.
+---Colliders are objects that represent a single rigid body in a physics simulation.
+---
+---They can have forces applied to them and collide with other colliders.
---
---@class lovr.Collider
local Collider = {}
---
----Attaches a Shape to the collider. Attached shapes will collide with other shapes in the world.
+---Attaches a Shape to the collider.
+---
+---Attached shapes will collide with other shapes in the world.
---
---@param shape lovr.Shape # The Shape to attach.
function Collider:addShape(shape) end
@@ -215,6 +277,10 @@ function Collider:addShape(shape) end
---
---Applies a force to the Collider.
---
+---
+---### NOTE:
+---If the Collider is asleep, it will need to be woken up with `Collider:setAwake` for this function to have any affect.
+---
---@overload fun(self: lovr.Collider, x: number, y: number, z: number, px: number, py: number, pz: number)
---@param x number # The x component of the force to apply.
---@param y number # The y component of the force to apply.
@@ -224,6 +290,10 @@ function Collider:applyForce(x, y, z) end
---
---Applies torque to the Collider.
---
+---
+---### NOTE:
+---If the Collider is asleep, it will need to be woken up with `Collider:setAwake` for this function to have any affect.
+---
---@param x number # The x component of the torque.
---@param y number # The y component of the torque.
---@param z number # The z component of the torque.
@@ -232,6 +302,10 @@ function Collider:applyTorque(x, y, z) end
---
---Destroy the Collider, removing it from the World.
---
+---
+---### NOTE:
+---Calling functions on the collider after destroying it is a bad idea.
+---
function Collider:destroy() end
---
@@ -246,7 +320,13 @@ function Collider:destroy() end
function Collider:getAABB() end
---
----Returns the angular damping parameters of the Collider. Angular damping makes things less "spinny", making them slow down their angular velocity over time.
+---Returns the angular damping parameters of the Collider.
+---
+---Angular damping makes things less "spinny", making them slow down their angular velocity over time.
+---
+---
+---### NOTE:
+---Angular damping can also be set on the World.
---
---@return number damping # The angular damping.
---@return number threshold # Velocity limit below which the damping is not applied.
@@ -261,7 +341,11 @@ function Collider:getAngularDamping() end
function Collider:getAngularVelocity() end
---
----Returns the friction of the Collider. By default, the friction of two Colliders is combined (multiplied) when they collide to generate a friction force. The initial friction is 0.
+---Returns the friction of the Collider.
+---
+---By default, the friction of two Colliders is combined (multiplied) when they collide to generate a friction force.
+---
+---The initial friction is 0.
---
---@return number friction # The friction of the Collider.
function Collider:getFriction() end
@@ -273,14 +357,28 @@ function Collider:getFriction() end
function Collider:getJoints() end
---
----Returns the Collider's linear damping parameters. Linear damping is similar to drag or air resistance, slowing the Collider down over time.
+---Returns the Collider's linear damping parameters.
+---
+---Linear damping is similar to drag or air resistance, slowing the Collider down over time.
+---
+---
+---### NOTE:
+---A linear damping of 0 means the Collider won't slow down over time.
+---
+---This is the default.
+---
+---Linear damping can also be set on the World using `World:setLinearDamping`, which will affect all new colliders.
---
---@return number damping # The linear damping.
---@return number threshold # Velocity limit below which the damping is not applied.
function Collider:getLinearDamping() end
---
----Returns the linear velocity of the Collider. This is how fast the Collider is moving. There is also angular velocity, which is how fast the Collider is spinning.
+---Returns the linear velocity of the Collider.
+---
+---This is how fast the Collider is moving.
+---
+---There is also angular velocity, which is how fast the Collider is spinning.
---
---@return number vx # The x velocity of the Collider, in meters per second.
---@return number vy # The y velocity of the Collider, in meters per second.
@@ -340,7 +438,9 @@ function Collider:getLocalPoint(wx, wy, wz) end
function Collider:getLocalVector(wx, wy, wz) end
---
----Returns the total mass of the Collider. The mass of a Collider depends on its attached shapes.
+---Returns the total mass of the Collider.
+---
+---The mass of a Collider depends on its attached shapes.
---
---@return number mass # The mass of the Collider, in kilograms.
function Collider:getMass() end
@@ -385,7 +485,11 @@ function Collider:getPose() end
function Collider:getPosition() end
---
----Returns the restitution (bounciness) of the Collider. By default, the restitution of two Colliders is combined (the max is used) when they collide to cause them to bounce away from each other. The initial restitution is 0.
+---Returns the restitution (bounciness) of the Collider.
+---
+---By default, the restitution of two Colliders is combined (the max is used) when they collide to cause them to bounce away from each other.
+---
+---The initial restitution is 0.
---
---@return number restitution # The restitution of the Collider.
function Collider:getRestitution() end
@@ -399,18 +503,30 @@ function Collider:getShapes() end
---
---Returns the Collider's tag.
---
+---
+---### NOTE:
+---Collision between tags can be enabled and disabled using `World:enableCollisionBetween` and `World:disableCollisionBetween`.
+---
---@return string tag # The Collider's collision tag.
function Collider:getTag() end
---
---Returns the user data associated with the Collider.
---
+---
+---### NOTE:
+---User data can be useful to identify the Collider in callbacks.
+---
---@return any data # The custom value associated with the Collider.
function Collider:getUserData() end
---
---Returns the World the Collider is in.
---
+---
+---### NOTE:
+---Colliders can only be in one World at a time.
+---
---@return lovr.World world # The World the Collider is in.
function Collider:getWorld() end
@@ -451,23 +567,47 @@ function Collider:isGravityIgnored() end
---
---Returns whether the Collider is kinematic.
---
+---
+---### NOTE:
+---Kinematic colliders behave as though they have infinite mass, ignoring external forces like gravity, joints, or collisions (though non-kinematic colliders will collide with them). They can be useful for static objects like floors or walls.
+---
---@return boolean kinematic # Whether the Collider is kinematic.
function Collider:isKinematic() end
---
---Returns whether the Collider is allowed to sleep.
---
+---
+---### NOTE:
+---If sleeping is enabled, the simulation will put the Collider to sleep if it hasn't moved in a while. Sleeping colliders don't impact the physics simulation, which makes updates more efficient and improves physics performance.
+---
+---However, the physics engine isn't perfect at waking up sleeping colliders and this can lead to bugs where colliders don't react to forces or collisions properly.
+---
+---It is possible to set the default value for new colliders using `World:setSleepingAllowed`.
+---
+---Colliders can be manually put to sleep or woken up using `Collider:setAwake`.
+---
---@return boolean allowed # Whether the Collider can go to sleep.
function Collider:isSleepingAllowed() end
---
---Removes a Shape from the Collider.
---
+---
+---### NOTE:
+---Colliders without any shapes won't collide with anything.
+---
---@param shape lovr.Shape # The Shape to remove.
function Collider:removeShape(shape) end
---
----Sets the angular damping of the Collider. Angular damping makes things less "spinny", causing them to slow down their angular velocity over time. Damping is only applied when angular velocity is over the threshold value.
+---Sets the angular damping of the Collider.
+---
+---Angular damping makes things less "spinny", causing them to slow down their angular velocity over time. Damping is only applied when angular velocity is over the threshold value.
+---
+---
+---### NOTE:
+---Angular damping can also be set on the World.
---
---@param damping number # The angular damping.
---@param threshold? number # Velocity limit below which the damping is not applied.
@@ -482,13 +622,19 @@ function Collider:setAngularDamping(damping, threshold) end
function Collider:setAngularVelocity(vx, vy, vz) end
---
----Manually puts the Collider to sleep or wakes it up. You can do this if you know a Collider won't be touched for a while or if you need to it be active.
+---Manually puts the Collider to sleep or wakes it up.
+---
+---You can do this if you know a Collider won't be touched for a while or if you need to it be active.
---
---@param awake boolean # Whether the Collider should be awake.
function Collider:setAwake(awake) end
---
----Sets the friction of the Collider. By default, the friction of two Colliders is combined (multiplied) when they collide to generate a friction force. The initial friction is 0.
+---Sets the friction of the Collider.
+---
+---By default, the friction of two Colliders is combined (multiplied) when they collide to generate a friction force.
+---
+---The initial friction is 0.
---
---@param friction number # The new friction.
function Collider:setFriction(friction) end
@@ -502,18 +648,34 @@ function Collider:setGravityIgnored(ignored) end
---
---Sets whether the Collider is kinematic.
---
+---
+---### NOTE:
+---Kinematic colliders behave as though they have infinite mass, ignoring external forces like gravity, joints, or collisions (though non-kinematic colliders will collide with them). They can be useful for static objects like floors or walls.
+---
---@param kinematic boolean # Whether the Collider is kinematic.
function Collider:setKinematic(kinematic) end
---
----Sets the Collider's linear damping parameter. Linear damping is similar to drag or air resistance, slowing the Collider down over time. Damping is only applied when linear velocity is over the threshold value.
+---Sets the Collider's linear damping parameter.
+---
+---Linear damping is similar to drag or air resistance, slowing the Collider down over time. Damping is only applied when linear velocity is over the threshold value.
+---
+---
+---### NOTE:
+---A linear damping of 0 means the Collider won't slow down over time.
+---
+---This is the default.
+---
+---Linear damping can also be set on the World using `World:setLinearDamping`, which will affect all new colliders.
---
---@param damping number # The linear damping.
---@param threshold? number # Velocity limit below which the damping is not applied.
function Collider:setLinearDamping(damping, threshold) end
---
----Sets the linear velocity of the Collider directly. Usually it's preferred to use `Collider:applyForce` to change velocity since instantaneous velocity changes can lead to weird glitches.
+---Sets the linear velocity of the Collider directly.
+---
+---Usually it's preferred to use `Collider:applyForce` to change velocity since instantaneous velocity changes can lead to weird glitches.
---
---@param vx number # The x velocity of the Collider, in meters per second.
---@param vy number # The y velocity of the Collider, in meters per second.
@@ -566,7 +728,9 @@ function Collider:setPose(x, y, z, angle, ax, ay, az) end
function Collider:setPosition(x, y, z) end
---
----Sets the restitution (bounciness) of the Collider. By default, the restitution of two Colliders is combined (the max is used) when they collide to cause them to bounce away from each other. The initial restitution is 0.
+---Sets the restitution (bounciness) of the Collider.
+---
+---By default, the restitution of two Colliders is combined (the max is used) when they collide to cause them to bounce away from each other. The initial restitution is 0.
---
---@param restitution number # The new restitution.
function Collider:setRestitution(restitution) end
@@ -574,18 +738,36 @@ function Collider:setRestitution(restitution) end
---
---Sets whether the Collider is allowed to sleep.
---
+---
+---### NOTE:
+---If sleeping is enabled, the simulation will put the Collider to sleep if it hasn't moved in a while. Sleeping colliders don't impact the physics simulation, which makes updates more efficient and improves physics performance.
+---
+---However, the physics engine isn't perfect at waking up sleeping colliders and this can lead to bugs where colliders don't react to forces or collisions properly.
+---
+---It is possible to set the default value for new colliders using `World:setSleepingAllowed`.
+---
+---Colliders can be manually put to sleep or woken up using `Collider:setAwake`.
+---
---@param allowed boolean # Whether the Collider can go to sleep.
function Collider:setSleepingAllowed(allowed) end
---
---Sets the Collider's tag.
---
+---
+---### NOTE:
+---Collision between tags can be enabled and disabled using `World:enableCollisionBetween` and `World:disableCollisionBetween`.
+---
---@param tag string # The Collider's collision tag.
function Collider:setTag(tag) end
---
---Associates a custom value with the Collider.
---
+---
+---### NOTE:
+---User data can be useful to identify the Collider in callbacks.
+---
---@param data any # The custom value to associate with the Collider.
function Collider:setUserData(data) end
@@ -620,7 +802,9 @@ function CylinderShape:setLength(length) end
function CylinderShape:setRadius(radius) end
---
----A DistanceJoint is a type of `Joint` that tries to keep two colliders a fixed distance apart. The distance is determined by the initial distance between the anchor points. The joint allows for rotation on the anchor points.
+---A DistanceJoint is a type of `Joint` that tries to keep two colliders a fixed distance apart. The distance is determined by the initial distance between the anchor points.
+---
+---The joint allows for rotation on the anchor points.
---
---@class lovr.DistanceJoint
local DistanceJoint = {}
@@ -637,19 +821,25 @@ local DistanceJoint = {}
function DistanceJoint:getAnchors() end
---
----Returns the target distance for the DistanceJoint. The joint tries to keep the Colliders this far apart.
+---Returns the target distance for the DistanceJoint.
+---
+---The joint tries to keep the Colliders this far apart.
---
---@return number distance # The target distance.
function DistanceJoint:getDistance() end
---
----Returns the response time of the joint. See `World:setResponseTime` for more info.
+---Returns the response time of the joint.
+---
+---See `World:setResponseTime` for more info.
---
---@return number responseTime # The response time setting for the joint.
function DistanceJoint:getResponseTime() end
---
----Returns the tightness of the joint. See `World:setTightness` for how this affects the joint.
+---Returns the tightness of the joint.
+---
+---See `World:setTightness` for how this affects the joint.
---
---@return number tightness # The tightness of the joint.
function DistanceJoint:getTightness() end
@@ -666,19 +856,25 @@ function DistanceJoint:getTightness() end
function DistanceJoint:setAnchors(x1, y1, z1, x2, y2, z2) end
---
----Sets the target distance for the DistanceJoint. The joint tries to keep the Colliders this far apart.
+---Sets the target distance for the DistanceJoint.
+---
+---The joint tries to keep the Colliders this far apart.
---
---@param distance number # The new target distance.
function DistanceJoint:setDistance(distance) end
---
----Sets the response time of the joint. See `World:setResponseTime` for more info.
+---Sets the response time of the joint.
+---
+---See `World:setResponseTime` for more info.
---
---@param responseTime number # The new response time setting for the joint.
function DistanceJoint:setResponseTime(responseTime) end
---
----Sets the tightness of the joint. See `World:setTightness` for how this affects the joint.
+---Sets the tightness of the joint.
+---
+---See `World:setTightness` for how this affects the joint.
---
---@param tightness number # The tightness of the joint.
function DistanceJoint:setTightness(tightness) end
@@ -701,7 +897,9 @@ local HingeJoint = {}
function HingeJoint:getAnchors() end
---
----Get the angle between the two colliders attached to the HingeJoint. When the joint is created or when the anchor or axis is set, the current angle is the new "zero" angle.
+---Get the angle between the two colliders attached to the HingeJoint.
+---
+---When the joint is created or when the anchor or axis is set, the current angle is the new "zero" angle.
---
---@return number angle # The hinge angle, in radians.
function HingeJoint:getAngle() end
@@ -715,20 +913,26 @@ function HingeJoint:getAngle() end
function HingeJoint:getAxis() end
---
----Returns the upper and lower limits of the hinge angle. These will be between -π and π.
+---Returns the upper and lower limits of the hinge angle.
+---
+---These will be between -π and π.
---
---@return number lower # The lower limit, in radians.
---@return number upper # The upper limit, in radians.
function HingeJoint:getLimits() end
---
----Returns the lower limit of the hinge angle. This will be greater than -π.
+---Returns the lower limit of the hinge angle.
+---
+---This will be greater than -π.
---
---@return number limit # The lower limit, in radians.
function HingeJoint:getLowerLimit() end
---
----Returns the upper limit of the hinge angle. This will be less than π.
+---Returns the upper limit of the hinge angle.
+---
+---This will be less than π.
---
---@return number limit # The upper limit, in radians.
function HingeJoint:getUpperLimit() end
@@ -750,20 +954,26 @@ function HingeJoint:setAnchor(x, y, z) end
function HingeJoint:setAxis(x, y, z) end
---
----Sets the upper and lower limits of the hinge angle. These should be between -π and π.
+---Sets the upper and lower limits of the hinge angle.
+---
+---These should be between -π and π.
---
---@param lower number # The lower limit, in radians.
---@param upper number # The upper limit, in radians.
function HingeJoint:setLimits(lower, upper) end
---
----Sets the lower limit of the hinge angle. This should be greater than -π.
+---Sets the lower limit of the hinge angle.
+---
+---This should be greater than -π.
---
---@param limit number # The lower limit, in radians.
function HingeJoint:setLowerLimit(limit) end
---
----Sets the upper limit of the hinge angle. This should be less than π.
+---Sets the upper limit of the hinge angle.
+---
+---This should be less than π.
---
---@param limit number # The upper limit, in radians.
function HingeJoint:setUpperLimit(limit) end
@@ -777,10 +987,16 @@ local Joint = {}
---
---Destroy the Joint, removing it from Colliders it's attached to.
---
+---
+---### NOTE:
+---Calling functions on the Joint after destroying it is a bad idea.
+---
function Joint:destroy() end
---
----Returns the Colliders the Joint is attached to. All Joints are attached to two colliders.
+---Returns the Colliders the Joint is attached to.
+---
+---All Joints are attached to two colliders.
---
---@return lovr.Collider colliderA # The first Collider.
---@return lovr.Collider colliderB # The second Collider.
@@ -825,6 +1041,10 @@ local Shape = {}
---
---Destroy the Shape, removing it from Colliders it's attached to.
---
+---
+---### NOTE:
+---Calling functions on the Shape after destroying it is a bad idea.
+---
function Shape:destroy() end
---
@@ -841,6 +1061,10 @@ function Shape:getAABB() end
---
---Returns the Collider the Shape is attached to.
---
+---
+---### NOTE:
+---A Shape can only be attached to one Collider at a time.
+---
---@return lovr.Collider collider # The Collider the Shape is attached to.
function Shape:getCollider() end
@@ -881,17 +1105,27 @@ function Shape:getType() end
---
---Returns the user data associated with the Shape.
---
+---
+---### NOTE:
+---User data can be useful to identify the Shape in callbacks.
+---
---@return any data # The custom value associated with the Shape.
function Shape:getUserData() end
---
---Returns whether the Shape is enabled.
---
+---
+---### NOTE:
+---Disabled shapes won't collide with anything.
+---
---@return boolean enabled # Whether the Shape is enabled.
function Shape:isEnabled() end
---
----Returns whether the Shape is a sensor. Sensors do not trigger any collision response, but they still report collisions in `World:collide`.
+---Returns whether the Shape is a sensor.
+---
+---Sensors do not trigger any collision response, but they still report collisions in `World:collide`.
---
---@return boolean sensor # Whether the Shape is a sensor.
function Shape:isSensor() end
@@ -899,12 +1133,20 @@ function Shape:isSensor() end
---
---Enable or disable the Shape.
---
+---
+---### NOTE:
+---Disabled shapes won't collide with anything.
+---
---@param enabled boolean # Whether the Shape should be enabled.
function Shape:setEnabled(enabled) end
---
---Set the orientation of the Shape relative to its Collider.
---
+---
+---### NOTE:
+---If the Shape isn't attached to a Collider, this will error.
+---
---@param angle number # The number of radians the Shape is rotated.
---@param ax number # The x component of the rotation axis.
---@param ay number # The y component of the rotation axis.
@@ -914,13 +1156,19 @@ function Shape:setOrientation(angle, ax, ay, az) end
---
---Set the position of the Shape relative to its Collider.
---
+---
+---### NOTE:
+---If the Shape isn't attached to a Collider, this will error.
+---
---@param x number # The x offset.
---@param y number # The y offset.
---@param z number # The z offset.
function Shape:setPosition(x, y, z) end
---
----Sets whether this Shape is a sensor. Sensors do not trigger any collision response, but they still report collisions in `World:collide`.
+---Sets whether this Shape is a sensor.
+---
+---Sensors do not trigger any collision response, but they still report collisions in `World:collide`.
---
---@param sensor boolean # Whether the Shape should be a sensor.
function Shape:setSensor(sensor) end
@@ -928,6 +1176,10 @@ function Shape:setSensor(sensor) end
---
---Sets the user data associated with the Shape.
---
+---
+---### NOTE:
+---User data can be useful to identify the Shape in callbacks.
+---
---@param data any # The custom value associated with the Shape.
function Shape:setUserData(data) end
@@ -1012,11 +1264,29 @@ function SphereShape:setDimensions(radius) end
---
---A World is an object that holds the colliders, joints, and shapes in a physics simulation.
---
+---
+---### NOTE:
+---Be sure to update the World in `lovr.update` using `World:update`, otherwise everything will stand still.
+---
---@class lovr.World
local World = {}
---
----Attempt to collide two shapes. Internally this uses joints and forces to ensure the colliders attached to the shapes do not pass through each other. Collisions can be customized using friction and restitution (bounciness) parameters, and default to using a mix of the colliders' friction and restitution parameters. Usually this is called automatically by `World:update`.
+---Attempt to collide two shapes.
+---
+---Internally this uses joints and forces to ensure the colliders attached to the shapes do not pass through each other.
+---
+---Collisions can be customized using friction and restitution (bounciness) parameters, and default to using a mix of the colliders' friction and restitution parameters.
+---
+---Usually this is called automatically by `World:update`.
+---
+---
+---### NOTE:
+---For friction, numbers in the range of 0-1 are common, but larger numbers can also be used.
+---
+---For restitution, numbers in the range 0-1 should be used.
+---
+---This function respects collision tags, so using `World:disableCollisionBetween` and `World:enableCollisionBetween` will change the behavior of this function.
---
---@param shapeA lovr.Shape # The first shape.
---@param shapeB lovr.Shape # The second shape.
@@ -1026,18 +1296,30 @@ local World = {}
function World:collide(shapeA, shapeB, friction, restitution) end
---
----Detects which pairs of shapes in the world are near each other and could be colliding. After calling this function, the `World:overlaps` iterator can be used to iterate over the overlaps, and `World:collide` can be used to resolve a collision for the shapes (if any). Usually this is called automatically by `World:update`.
+---Detects which pairs of shapes in the world are near each other and could be colliding.
+---
+---After calling this function, the `World:overlaps` iterator can be used to iterate over the overlaps, and `World:collide` can be used to resolve a collision for the shapes (if any). Usually this is called automatically by `World:update`.
---
function World:computeOverlaps() end
---
---Destroy the World!
---
+---
+---### NOTE:
+---Bad things will happen if you destroy the world and then try to access it or anything that was in it.
+---
function World:destroy() end
---
---Disables collision between two collision tags.
---
+---
+---### NOTE:
+---Tags must be set up when creating the World, see `lovr.physics.newWorld`.
+---
+---By default, collision is enabled between all tags.
+---
---@param tag1 string # The first tag.
---@param tag2 string # The second tag.
function World:disableCollisionBetween(tag1, tag2) end
@@ -1045,12 +1327,24 @@ function World:disableCollisionBetween(tag1, tag2) end
---
---Enables collision between two collision tags.
---
+---
+---### NOTE:
+---Tags must be set up when creating the World, see `lovr.physics.newWorld`.
+---
+---By default, collision is enabled between all tags.
+---
---@param tag1 string # The first tag.
---@param tag2 string # The second tag.
function World:enableCollisionBetween(tag1, tag2) end
---
----Returns the angular damping parameters of the World. Angular damping makes things less "spinny", making them slow down their angular velocity over time.
+---Returns the angular damping parameters of the World.
+---
+---Angular damping makes things less "spinny", making them slow down their angular velocity over time.
+---
+---
+---### NOTE:
+---Angular damping can also be set on individual colliders.
---
---@return number damping # The angular damping.
---@return number threshold # Velocity limit below which the damping is not applied.
@@ -1072,7 +1366,17 @@ function World:getColliders() end
function World:getGravity() end
---
----Returns the linear damping parameters of the World. Linear damping is similar to drag or air resistance, slowing down colliders over time as they move.
+---Returns the linear damping parameters of the World.
+---
+---Linear damping is similar to drag or air resistance, slowing down colliders over time as they move.
+---
+---
+---### NOTE:
+---A linear damping of 0 means colliders won't slow down over time.
+---
+---This is the default.
+---
+---Linear damping can also be set on individual colliders.
---
---@return number damping # The linear damping.
---@return number threshold # Velocity limit below which the damping is not applied.
@@ -1081,15 +1385,21 @@ function World:getLinearDamping() end
---
---Returns the response time factor of the World.
---
----The response time controls how relaxed collisions and joints are in the physics simulation, and functions similar to inertia. A low response time means collisions are resolved quickly, and higher values make objects more spongy and soft.
+---The response time controls how relaxed collisions and joints are in the physics simulation, and functions similar to inertia.
---
----The value can be any positive number. It can be changed on a per-joint basis for `DistanceJoint` and `BallJoint` objects.
+---A low response time means collisions are resolved quickly, and higher values make objects more spongy and soft.
+---
+---The value can be any positive number.
+---
+---It can be changed on a per-joint basis for `DistanceJoint` and `BallJoint` objects.
---
---@return number responseTime # The response time setting for the World.
function World:getResponseTime() end
---
----Returns the tightness of the joint. See `World:setTightness` for how this affects the joint.
+---Returns the tightness of the joint.
+---
+---See `World:setTightness` for how this affects the joint.
---
---@return number tightness # The tightness of the joint.
function World:getTightness() end
@@ -1097,6 +1407,12 @@ function World:getTightness() end
---
---Returns whether collisions are currently enabled between two tags.
---
+---
+---### NOTE:
+---Tags must be set up when creating the World, see `lovr.physics.newWorld`.
+---
+---By default, collision is enabled between all tags.
+---
---@param tag1 string # The first tag.
---@param tag2 string # The second tag.
---@return boolean enabled # Whether or not two colliders with the specified tags will collide.
@@ -1105,6 +1421,18 @@ function World:isCollisionEnabledBetween(tag1, tag2) end
---
---Returns whether colliders can go to sleep in the World.
---
+---
+---### NOTE:
+---If sleeping is enabled, the World will try to detect colliders that haven't moved for a while and put them to sleep.
+---
+---Sleeping colliders don't impact the physics simulation, which makes updates more efficient and improves physics performance.
+---
+---However, the physics engine isn't perfect at waking up sleeping colliders and this can lead to bugs where colliders don't react to forces or collisions properly.
+---
+---This can be set on individual colliders.
+---
+---Colliders can be manually put to sleep or woken up using `Collider:setAwake`.
+---
---@return boolean allowed # Whether colliders can sleep.
function World:isSleepingAllowed() end
@@ -1134,6 +1462,17 @@ function World:newCapsuleCollider(x, y, z, radius, length) end
---
---Adds a new Collider to the World.
---
+---
+---### NOTE:
+---This function creates a collider without any shapes attached to it, which means it won't collide with anything.
+---
+---To add a shape to the collider, use `Collider:addShape`, or use one of the following functions to create the collider:
+---
+---- `World:newBoxCollider`
+---- `World:newCapsuleCollider`
+---- `World:newCylinderCollider`
+---- `World:newSphereCollider`
+---
---@param x? number # The x position of the Collider.
---@param y? number # The y position of the Collider.
---@param z? number # The z position of the Collider.
@@ -1171,7 +1510,9 @@ function World:newMeshCollider(vertices, indices) end
function World:newSphereCollider(x, y, z, radius) end
---
----Returns an iterator that can be used to iterate over "overlaps", or potential collisions between pairs of shapes in the World. This should be called after using `World:detectOverlaps` to compute the list of overlaps. Usually this is called automatically by `World:update`.
+---Returns an iterator that can be used to iterate over "overlaps", or potential collisions between pairs of shapes in the World.
+---
+---This should be called after using `World:detectOverlaps` to compute the list of overlaps. Usually this is called automatically by `World:update`.
---
---@return function iterator # A Lua iterator, usable in a for loop.
function World:overlaps() end
@@ -1179,6 +1520,10 @@ function World:overlaps() end
---
---Casts a ray through the World, calling a function every time the ray intersects with a Shape.
---
+---
+---### NOTE:
+---The callback is passed the shape that was hit, the hit position (in world coordinates), and the normal vector of the hit.
+---
---@param x1 number # The x coordinate of the starting position of the ray.
---@param y1 number # The y coordinate of the starting position of the ray.
---@param z1 number # The z coordinate of the starting position of the ray.
@@ -1189,7 +1534,13 @@ function World:overlaps() end
function World:raycast(x1, y1, z1, x2, y2, z2, callback) end
---
----Sets the angular damping of the World. Angular damping makes things less "spinny", making them slow down their angular velocity over time. Damping is only applied when angular velocity is over the threshold value.
+---Sets the angular damping of the World.
+---
+---Angular damping makes things less "spinny", making them slow down their angular velocity over time. Damping is only applied when angular velocity is over the threshold value.
+---
+---
+---### NOTE:
+---Angular damping can also be set on individual colliders.
---
---@param damping number # The angular damping.
---@param threshold? number # Velocity limit below which the damping is not applied.
@@ -1204,7 +1555,17 @@ function World:setAngularDamping(damping, threshold) end
function World:setGravity(xg, yg, zg) end
---
----Sets the linear damping of the World. Linear damping is similar to drag or air resistance, slowing down colliders over time as they move. Damping is only applied when linear velocity is over the threshold value.
+---Sets the linear damping of the World.
+---
+---Linear damping is similar to drag or air resistance, slowing down colliders over time as they move. Damping is only applied when linear velocity is over the threshold value.
+---
+---
+---### NOTE:
+---A linear damping of 0 means colliders won't slow down over time.
+---
+---This is the default.
+---
+---Linear damping can also be set on individual colliders.
---
---@param damping number # The linear damping.
---@param threshold? number # Velocity limit below which the damping is not applied.
@@ -1213,9 +1574,13 @@ function World:setLinearDamping(damping, threshold) end
---
---Sets the response time factor of the World.
---
----The response time controls how relaxed collisions and joints are in the physics simulation, and functions similar to inertia. A low response time means collisions are resolved quickly, and higher values make objects more spongy and soft.
+---The response time controls how relaxed collisions and joints are in the physics simulation, and functions similar to inertia.
---
----The value can be any positive number. It can be changed on a per-joint basis for `DistanceJoint` and `BallJoint` objects.
+---A low response time means collisions are resolved quickly, and higher values make objects more spongy and soft.
+---
+---The value can be any positive number.
+---
+---It can be changed on a per-joint basis for `DistanceJoint` and `BallJoint` objects.
---
---@param responseTime number # The new response time setting for the World.
function World:setResponseTime(responseTime) end
@@ -1223,13 +1588,33 @@ function World:setResponseTime(responseTime) end
---
---Sets whether colliders can go to sleep in the World.
---
+---
+---### NOTE:
+---If sleeping is enabled, the World will try to detect colliders that haven't moved for a while and put them to sleep.
+---
+---Sleeping colliders don't impact the physics simulation, which makes updates more efficient and improves physics performance.
+---
+---However, the physics engine isn't perfect at waking up sleeping colliders and this can lead to bugs where colliders don't react to forces or collisions properly.
+---
+---This can be set on individual colliders.
+---
+---Colliders can be manually put to sleep or woken up using `Collider:setAwake`.
+---
---@param allowed boolean # Whether colliders can sleep.
function World:setSleepingAllowed(allowed) end
---
---Sets the tightness of joints in the World.
---
----The tightness controls how much force is applied to colliders connected by joints. With a value of 0, no force will be applied and joints won't have any effect. With a tightness of 1, a strong force will be used to try to keep the Colliders constrained. A tightness larger than 1 will overcorrect the joints, which can sometimes be desirable. Negative tightness values are not supported.
+---The tightness controls how much force is applied to colliders connected by joints.
+---
+---With a value of 0, no force will be applied and joints won't have any effect.
+---
+---With a tightness of 1, a strong force will be used to try to keep the Colliders constrained.
+---
+---A tightness larger than 1 will overcorrect the joints, which can sometimes be desirable.
+---
+---Negative tightness values are not supported.
---
---@param tightness number # The new tightness for the World.
function World:setTightness(tightness) end
@@ -1237,6 +1622,25 @@ function World:setTightness(tightness) end
---
---Updates the World, advancing the physics simulation forward in time and resolving collisions between colliders in the World.
---
+---
+---### NOTE:
+---It is common to pass the `dt` variable from `lovr.update` into this function.
+---
+---The default collision resolver function is:
+---
+--- function defaultResolver(world)
+--- world:computeOverlaps()
+--- for shapeA, shapeB in world:overlaps() do
+--- world:collide(shapeA, shapeB)
+--- end
+--- end
+---
+---Additional logic could be introduced to the collision resolver function to add custom collision behavior or to change the collision parameters (like friction and restitution) on a per-collision basis.
+---
+---> If possible, use a fixed timestep value for updating the World. It will greatly improve the
+---> accuracy of the simulation and reduce bugs. For more information on implementing a fixed
+---> timestep loop, see [this article](http://gafferongames.com/game-physics/fix-your-timestep/).
+---
---@param dt number # The amount of time to advance the simulation forward.
---@param resolver? function # The collision resolver function to use. This will be called before updating to allow for custom collision processing. If absent, a default will be used.
function World:update(dt, resolver) end
diff --git a/meta/3rd/lovr/library/lovr.system.lua b/meta/3rd/lovr/library/lovr.system.lua
index d3255f75..35161332 100644
--- a/meta/3rd/lovr/library/lovr.system.lua
+++ b/meta/3rd/lovr/library/lovr.system.lua
@@ -19,7 +19,13 @@ function lovr.system.getCoreCount() end
function lovr.system.getOS() end
---
----Requests permission to use a feature. Usually this will pop up a dialog box that the user needs to confirm. Once the permission request has been acknowledged, the `lovr.permission` callback will be called with the result. Currently, this is only used for requesting microphone access on Android devices.
+---Requests permission to use a feature.
+---
+---Usually this will pop up a dialog box that the user needs to confirm.
+---
+---Once the permission request has been acknowledged, the `lovr.permission` callback will be called with the result.
+---
+---Currently, this is only used for requesting microphone access on Android devices.
---
---@param permission lovr.Permission # The permission to request.
function lovr.system.requestPermission(permission) end
diff --git a/meta/3rd/lovr/library/lovr.thread.lua b/meta/3rd/lovr/library/lovr.thread.lua
index ca329a6b..08619426 100644
--- a/meta/3rd/lovr/library/lovr.thread.lua
+++ b/meta/3rd/lovr/library/lovr.thread.lua
@@ -5,18 +5,26 @@
---
---These are operating system level threads, which are different from Lua coroutines.
---
----Threads are useful for performing expensive background computation without affecting the framerate or performance of the main thread. Some examples of this include asset loading, networking and network requests, and physics simulation.
+---Threads are useful for performing expensive background computation without affecting the framerate or performance of the main thread.
+---
+---Some examples of this include asset loading, networking and network requests, and physics simulation.
---
---Threads come with some caveats:
---
----- Threads run in a bare Lua environment. The `lovr` module (and any of lovr's modules) need to
+---- Threads run in a bare Lua environment.
+---
+---The `lovr` module (and any of lovr's modules) need to
--- be required before they can be used.
--- - To get `require` to work properly, add `require 'lovr.filesystem'` to the thread code.
----- Threads are completely isolated from other threads. They do not have access to the variables
+---- Threads are completely isolated from other threads.
+---
+---They do not have access to the variables
--- or functions of other threads, and communication between threads must be coordinated through
--- `Channel` objects.
---- The graphics module (or any functions that perform rendering) cannot be used in a thread.
---- Note that this includes creating graphics objects like Models and Textures. There are "data"
+--- Note that this includes creating graphics objects like Models and Textures.
+---
+---There are "data"
--- equivalent `ModelData` and `Image` objects that can be used in threads though.
---- `lovr.event.pump` cannot be called from a thread.
---- Crashes or problems can happen if two threads access the same object at the same time, so
@@ -35,6 +43,16 @@ function lovr.thread.getChannel(name) end
---
---Creates a new Thread from Lua code.
---
+---
+---### NOTE:
+---The Thread won\'t start running immediately.
+---
+---Use `Thread:start` to start it.
+---
+---The string argument is assumed to be a filename if there isn't a newline in the first 1024 characters.
+---
+---For really short thread code, an extra newline can be added to trick LÖVR into loading it properly.
+---
---@overload fun(filename: string):lovr.Thread
---@overload fun(blob: lovr.Blob):lovr.Thread
---@param code string # The code to run in the Thread.
@@ -42,7 +60,13 @@ function lovr.thread.getChannel(name) end
function lovr.thread.newThread(code) end
---
----A Channel is an object used to communicate between `Thread` objects. Channels are obtained by name using `lovr.thread.getChannel`. Different threads can send messages on the same Channel to communicate with each other. Messages can be sent and received on a Channel using `Channel:push` and `Channel:pop`, and are received in a first-in-first-out fashion. The following types of data can be passed through Channels: nil, boolean, number, string, and any LÖVR object.
+---A Channel is an object used to communicate between `Thread` objects.
+---
+---Channels are obtained by name using `lovr.thread.getChannel`.
+---
+---Different threads can send messages on the same Channel to communicate with each other.
+---
+---Messages can be sent and received on a Channel using `Channel:push` and `Channel:pop`, and are received in a first-in-first-out fashion. The following types of data can be passed through Channels: nil, boolean, number, string, and any LÖVR object.
---
---@class lovr.Channel
local Channel = {}
@@ -53,28 +77,52 @@ local Channel = {}
function Channel:clear() end
---
----Returns whether or not the message with the given ID has been read. Every call to `Channel:push` returns a message ID.
+---Returns whether or not the message with the given ID has been read.
+---
+---Every call to `Channel:push` returns a message ID.
---
---@param id number # The ID of the message to check.
---@return boolean read # Whether the message has been read.
function Channel:hasRead(id) end
---
----Returns a message from the Channel without popping it from the queue. If the Channel is empty, `nil` is returned. This can be useful to determine if the Channel is empty.
+---Returns a message from the Channel without popping it from the queue.
+---
+---If the Channel is empty, `nil` is returned.
+---
+---This can be useful to determine if the Channel is empty.
+---
+---
+---### NOTE:
+---The second return value can be used to detect if a `nil` message is in the queue.
---
---@return any message # The message, or `nil` if there is no message.
---@return boolean present # Whether a message was returned (use to detect nil).
function Channel:peek() end
---
----Pops a message from the Channel. If the Channel is empty, an optional timeout argument can be used to wait for a message, otherwise `nil` is returned.
+---Pops a message from the Channel.
+---
+---If the Channel is empty, an optional timeout argument can be used to wait for a message, otherwise `nil` is returned.
+---
+---
+---### NOTE:
+---Threads can get stuck forever waiting on Channel messages, so be careful.
---
---@param wait? number # How long to wait for a message to be popped, in seconds. `true` can be used to wait forever and `false` can be used to avoid waiting.
---@return any message # The received message, or `nil` if nothing was received.
function Channel:pop(wait) end
---
----Pushes a message onto the Channel. The following types of data can be pushed: nil, boolean, number, string, and userdata. Tables should be serialized to strings.
+---Pushes a message onto the Channel.
+---
+---The following types of data can be pushed: nil, boolean, number, string, and userdata.
+---
+---Tables should be serialized to strings.
+---
+---
+---### NOTE:
+---Threads can get stuck forever waiting on Channel messages, so be careful.
---
---@param message any # The message to push.
---@param wait? number # How long to wait for the message to be popped, in seconds. `true` can be used to wait forever and `false` can be used to avoid waiting.
@@ -83,7 +131,11 @@ function Channel:pop(wait) end
function Channel:push(message, wait) end
---
----A Thread is an object that runs a chunk of Lua code in the background. Threads are completely isolated from other threads, meaning they have their own Lua context and can't access the variables and functions of other threads. Communication between threads is limited and is accomplished by using `Channel` objects.
+---A Thread is an object that runs a chunk of Lua code in the background.
+---
+---Threads are completely isolated from other threads, meaning they have their own Lua context and can't access the variables and functions of other threads.
+---
+---Communication between threads is limited and is accomplished by using `Channel` objects.
---
---To get `require` to work properly, add `require 'lovr.filesystem'` to the thread code.
---
diff --git a/meta/3rd/lovr/library/lovr.timer.lua b/meta/3rd/lovr/library/lovr.timer.lua
index b4693e4c..4bcb02f1 100644
--- a/meta/3rd/lovr/library/lovr.timer.lua
+++ b/meta/3rd/lovr/library/lovr.timer.lua
@@ -1,7 +1,9 @@
---@meta
---
----The `lovr.timer` module provides a few functions that deal with time. All times are measured in seconds.
+---The `lovr.timer` module provides a few functions that deal with time.
+---
+---All times are measured in seconds.
---
---@class lovr.timer
lovr.timer = {}
@@ -13,7 +15,15 @@ lovr.timer = {}
function lovr.timer.getAverageDelta() end
---
----Returns the time between the last two frames. This is the same value as the `dt` argument provided to `lovr.update`.
+---Returns the time between the last two frames.
+---
+---This is the same value as the `dt` argument provided to `lovr.update`.
+---
+---
+---### NOTE:
+---The return value of this function will remain the same until `lovr.timer.step` is called.
+---
+---This function should not be used to measure times for game behavior or benchmarking, use `lovr.timer.getTime` for that.
---
---@return number dt # The delta time, in seconds.
function lovr.timer.getDelta() end
@@ -25,19 +35,25 @@ function lovr.timer.getDelta() end
function lovr.timer.getFPS() end
---
----Returns the time since some time in the past. This can be used to measure the difference between two points in time.
+---Returns the time since some time in the past.
+---
+---This can be used to measure the difference between two points in time.
---
---@return number time # The current time, in seconds.
function lovr.timer.getTime() end
---
----Sleeps the application for a specified number of seconds. While the game is asleep, no code will be run, no graphics will be drawn, and the window will be unresponsive.
+---Sleeps the application for a specified number of seconds.
+---
+---While the game is asleep, no code will be run, no graphics will be drawn, and the window will be unresponsive.
---
---@param duration number # The number of seconds to sleep for.
function lovr.timer.sleep(duration) end
---
----Steps the timer, returning the new delta time. This is called automatically in `lovr.run` and it's used to calculate the new `dt` to pass to `lovr.update`.
+---Steps the timer, returning the new delta time.
+---
+---This is called automatically in `lovr.run` and it's used to calculate the new `dt` to pass to `lovr.update`.
---
---@return number delta # The amount of time since the last call to this function, in seconds.
function lovr.timer.step() end
diff --git a/script/client.lua b/script/client.lua
index 0388ff39..f265cf9a 100644
--- a/script/client.lua
+++ b/script/client.lua
@@ -197,7 +197,7 @@ end
---@field prop? string
---@field value any
---@field action '"add"'|'"set"'|'"prop"'
----@field isGlobal? boolean
+---@field global? boolean
---@field uri? uri
---@param cfg table
@@ -298,7 +298,7 @@ local function tryModifyClientGlobal(finalChanges)
local changes = {}
for i = #finalChanges, 1, -1 do
local change = finalChanges[i]
- if change.isGlobal then
+ if change.global then
changes[#changes+1] = change
finalChanges[i] = finalChanges[#finalChanges]
finalChanges[#finalChanges] = nil
@@ -341,7 +341,7 @@ function m.setConfig(changes, onlyMemory)
xpcall(function ()
local ws = require 'workspace'
if #ws.folders == 0 then
- tryModifyClient(finalChanges)
+ tryModifyClient(nil, finalChanges)
return
end
tryModifyClientGlobal(finalChanges)
diff --git a/script/config/config.lua b/script/config/config.lua
index a53b77b5..8c06278f 100644
--- a/script/config/config.lua
+++ b/script/config/config.lua
@@ -129,7 +129,7 @@ end, function (self, subkey, subvalue, sep)
self.sep = sep
end)
-register('Or', {}, function (self, value)
+register('Or', nil, function (self, value)
for _, sub in ipairs(self.subs) do
if sub:checker(value) then
return true
@@ -208,11 +208,14 @@ local Template = {
['Lua.hint.arrayIndex'] = Type.Boolean >> 'Auto',
['Lua.window.statusBar'] = Type.Boolean >> true,
['Lua.window.progressBar'] = Type.Boolean >> true,
+ ['Lua.format.enable'] = Type.Boolean >> true,
+ ['Lua.format.defaultConfig'] = Type.Hash(Type.String, Type.String)
+ >> {},
['Lua.IntelliSense.traceLocalSet'] = Type.Boolean >> false,
['Lua.IntelliSense.traceReturn'] = Type.Boolean >> false,
['Lua.IntelliSense.traceBeSetted'] = Type.Boolean >> false,
['Lua.IntelliSense.traceFieldInject'] = Type.Boolean >> false,
- ['Lua.telemetry.enable'] = Type.Or(Type.Boolean >> false, Type.Nil),
+ ['Lua.telemetry.enable'] = Type.Or(Type.Boolean >> false, Type.Nil) >> nil,
['files.associations'] = Type.Hash(Type.String, Type.String),
['files.exclude'] = Type.Hash(Type.String, Type.Boolean),
['editor.semanticHighlighting.enabled'] = Type.Or(Type.Boolean, Type.String),
diff --git a/script/core/formatting.lua b/script/core/formatting.lua
index 6c57b8c2..49da6861 100644
--- a/script/core/formatting.lua
+++ b/script/core/formatting.lua
@@ -1,11 +1,11 @@
local codeFormat = require("code_format")
-local files = require("files")
-local log = require("log")
+local files = require("files")
+local log = require("log")
-return function(uri)
+return function(uri, options)
local text = files.getText(uri)
local ast = files.getState(uri)
- local status, formattedText = codeFormat.format(uri, text)
+ local status, formattedText = codeFormat.format(uri, text, options)
if not status then
if formattedText ~= nil then
diff --git a/script/core/rangeformatting.lua b/script/core/rangeformatting.lua
index de9516c1..ccf2d21f 100644
--- a/script/core/rangeformatting.lua
+++ b/script/core/rangeformatting.lua
@@ -3,10 +3,10 @@ local files = require("files")
local log = require("log")
local converter = require("proto.converter")
-return function(uri, range)
+return function(uri, range, options)
local text = files.getText(uri)
local status, formattedText, startLine, endLine = codeFormat.range_format(
- uri, text, range.start.line, range["end"].line)
+ uri, text, range.start.line, range["end"].line, options)
if not status then
if formattedText ~= nil then
diff --git a/script/global.d.lua b/script/global.d.lua
index 0435293e..ad4fb364 100644
--- a/script/global.d.lua
+++ b/script/global.d.lua
@@ -33,3 +33,9 @@ FOOTPRINT = false
---trace rpc, use command line: --rpclog=true
---@type boolean
RPCLOG = false
+
+--enable preview features.
+--
+--the current version is `formatting`
+---@type boolean
+PREVIEW = false
diff --git a/script/parser/guide.lua b/script/parser/guide.lua
index 638c08bf..10b2badb 100644
--- a/script/parser/guide.lua
+++ b/script/parser/guide.lua
@@ -256,7 +256,7 @@ end
---@param obj parser.object
---@return parser.object
function m.getParentFunction(obj)
- for _ = 1, 1000 do
+ for _ = 1, 10000 do
obj = obj.parent
if not obj then
break
@@ -273,7 +273,7 @@ end
---@param obj parser.object
---@return parser.object
function m.getBlock(obj)
- for _ = 1, 1000 do
+ for _ = 1, 10000 do
if not obj then
return nil
end
@@ -302,7 +302,7 @@ end
---@param obj parser.object
---@return parser.object
function m.getParentBlock(obj)
- for _ = 1, 1000 do
+ for _ = 1, 10000 do
obj = obj.parent
if not obj then
return nil
@@ -319,7 +319,7 @@ end
---@param obj parser.object
---@return parser.object
function m.getBreakBlock(obj)
- for _ = 1, 1000 do
+ for _ = 1, 10000 do
obj = obj.parent
if not obj then
return nil
@@ -339,7 +339,7 @@ end
---@param obj parser.object
---@return parser.object
function m.getDocState(obj)
- for _ = 1, 1000 do
+ for _ = 1, 10000 do
local parent = obj.parent
if not parent then
return obj
@@ -356,7 +356,7 @@ end
---@param obj parser.object
---@return parser.object
function m.getParentType(obj, want)
- for _ = 1, 1000 do
+ for _ = 1, 10000 do
obj = obj.parent
if not obj then
return nil
@@ -376,7 +376,7 @@ function m.getRoot(obj)
if source._root then
return source._root
end
- for _ = 1, 1000 do
+ for _ = 1, 10000 do
if obj.type == 'main' then
source._root = obj
return obj
@@ -445,7 +445,7 @@ end
---@param pos integer {comment = '可见位置'}
function m.getLocal(block, name, pos)
block = m.getBlock(block)
- for _ = 1, 1000 do
+ for _ = 1, 10000 do
if not block then
return nil
end
@@ -497,7 +497,7 @@ end
---@param name string {comment = '标签名'}
function m.getLabel(block, name)
block = m.getBlock(block)
- for _ = 1, 1000 do
+ for _ = 1, 10000 do
if not block then
return nil
end
diff --git a/script/provider/capability.lua b/script/provider/capability.lua
index e012f4b4..ba5690bf 100644
--- a/script/provider/capability.lua
+++ b/script/provider/capability.lua
@@ -7,17 +7,6 @@ local define = require 'proto.define'
require 'provider.semantic-tokens'
require 'provider.formatting'
-local function toArray(map)
- local array = {}
- for k in pairs(map) do
- array[#array+1] = k
- end
- table.sort(array, function (a, b)
- return map[a] < map[b]
- end)
- return array
-end
-
local m = {}
local function testFileEvents(initer)
@@ -58,8 +47,27 @@ local function testFileEvents(initer)
}
end
-function m.getIniter()
- local initer = {
+m.fillings = {}
+
+local function mergeFillings(provider)
+ for _, filling in ipairs(m.fillings) do
+ for k, v in pairs(filling) do
+ if type(v) == 'table' then
+ if not provider[k] then
+ provider[k] = {}
+ end
+ for kk, vv in pairs(v) do
+ provider[k][kk] = vv
+ end
+ else
+ provider[k] = v
+ end
+ end
+ end
+end
+
+function m.getProvider()
+ local provider = {
offsetEncoding = client.getOffsetEncoding(),
-- 文本同步方式
textDocumentSync = {
@@ -68,53 +76,6 @@ function m.getIniter()
-- 文本增量更新
change = 2,
},
-
- hoverProvider = true,
- definitionProvider = true,
- typeDefinitionProvider = true,
- referencesProvider = true,
- renameProvider = {
- prepareProvider = true,
- },
- documentSymbolProvider = true,
- workspaceSymbolProvider = true,
- documentHighlightProvider = true,
- codeActionProvider = {
- codeActionKinds = {
- '',
- 'quickfix',
- 'refactor.rewrite',
- 'refactor.extract',
- },
- resolveProvider = false,
- },
- signatureHelpProvider = {
- triggerCharacters = { '(', ',' },
- },
- executeCommandProvider = {
- commands = {
- 'lua.removeSpace',
- 'lua.solve',
- 'lua.jsonToLua',
- 'lua.setConfig',
- 'lua.autoRequire',
- },
- },
- foldingRangeProvider = true,
- documentOnTypeFormattingProvider = {
- firstTriggerCharacter = '\n',
- moreTriggerCharacter = nil, -- string[]
- },
- semanticTokensProvider = {
- legend = {
- tokenTypes = toArray(define.TokenTypes),
- tokenModifiers = toArray(define.TokenModifiers),
- },
- range = true,
- full = false,
- },
- documentFormattingProvider = true,
- documentRangeFormattingProvider = true
}
--testFileEvents()
@@ -122,14 +83,20 @@ function m.getIniter()
nonil.enable()
if not client.info.capabilities.textDocument.completion.dynamicRegistration
or not client.info.capabilities.workspace.configuration then
- initer.completionProvider = {
+ provider.completionProvider = {
resolveProvider = true,
triggerCharacters = completion.allWords(),
}
end
nonil.disable()
- return initer
+ mergeFillings(provider)
+
+ return provider
+end
+
+function m.filling(t)
+ m.fillings[#m.fillings+1] = t
end
return m
diff --git a/script/provider/formatting.lua b/script/provider/formatting.lua
index 9392259e..f73b0dc0 100644
--- a/script/provider/formatting.lua
+++ b/script/provider/formatting.lua
@@ -5,6 +5,7 @@ local fs = require 'bee.filesystem'
local fw = require 'filewatch'
local util = require 'utility'
local diagnostics = require 'provider.diagnostic'
+local config = require 'config'
local loadedUris = {}
@@ -31,10 +32,23 @@ fw.event(function (ev, path)
end
end)
+config.watch(function (uri, key, value)
+ if key == "Lua.format.defaultConfig" then
+ codeFormat.set_default_config(value)
+ end
+end)
+
local m = {}
+m.loadedDefaultConfig = false
+
---@param uri uri
function m.updateConfig(uri)
+ if not m.loadedDefaultConfig then
+ m.loadedDefaultConfig = true
+ codeFormat.set_default_config(config.get(uri, 'Lua.format.defaultConfig'))
+ end
+
local currentUri = uri
while true do
currentUri = currentUri:match('^(.+)/[^/]*$')
diff --git a/script/provider/provider.lua b/script/provider/provider.lua
index df226c3f..3e8fec24 100644
--- a/script/provider/provider.lua
+++ b/script/provider/provider.lua
@@ -61,6 +61,12 @@ m.attributes = {}
function m.register(method)
return function (attrs)
m.attributes[method] = attrs
+ if attrs.preview and not PREVIEW then
+ return
+ end
+ if attrs.capability then
+ cap.filling(attrs.capability)
+ end
proto.on(method, attrs[1])
end
end
@@ -101,7 +107,7 @@ m.register 'initialize' {
end
return {
- capabilities = cap.getIniter(),
+ capabilities = cap.getProvider(),
serverInfo = {
name = 'sumneko.lua',
},
@@ -261,6 +267,9 @@ m.register 'textDocument/didChange' {
}
m.register 'textDocument/hover' {
+ capability = {
+ hoverProvider = true,
+ },
abortByFileUpdate = true,
---@async
function (params)
@@ -299,6 +308,9 @@ m.register 'textDocument/hover' {
}
m.register 'textDocument/definition' {
+ capability = {
+ definitionProvider = true,
+ },
abortByFileUpdate = true,
---@async
function (params)
@@ -338,6 +350,9 @@ m.register 'textDocument/definition' {
}
m.register 'textDocument/typeDefinition' {
+ capability = {
+ typeDefinitionProvider = true,
+ },
abortByFileUpdate = true,
---@async
function (params)
@@ -377,6 +392,9 @@ m.register 'textDocument/typeDefinition' {
}
m.register 'textDocument/references' {
+ capability = {
+ referencesProvider = true,
+ },
abortByFileUpdate = true,
---@async
function (params)
@@ -404,10 +422,14 @@ m.register 'textDocument/references' {
}
m.register 'textDocument/documentHighlight' {
- abortByFileUpdate = true,
+ capability = {
+ documentHighlightProvider = true,
+ },
+ ---@async
function (params)
local core = require 'core.highlight'
local uri = files.getRealUri(params.textDocument.uri)
+ workspace.awaitReady(uri)
if not files.exists(uri) then
return nil
end
@@ -428,6 +450,11 @@ m.register 'textDocument/documentHighlight' {
}
m.register 'textDocument/rename' {
+ capability = {
+ renameProvider = {
+ prepareProvider = true,
+ },
+ },
abortByFileUpdate = true,
---@async
function (params)
@@ -631,6 +658,11 @@ m.register 'completionItem/resolve' {
}
m.register 'textDocument/signatureHelp' {
+ capability = {
+ signatureHelpProvider = {
+ triggerCharacters = { '(', ',' },
+ },
+ },
abortByFileUpdate = true,
---@async
function (params)
@@ -677,6 +709,9 @@ m.register 'textDocument/signatureHelp' {
}
m.register 'textDocument/documentSymbol' {
+ capability = {
+ documentSymbolProvider = true,
+ },
abortByFileUpdate = true,
---@async
function (params)
@@ -723,6 +758,17 @@ m.register 'textDocument/documentSymbol' {
}
m.register 'textDocument/codeAction' {
+ capability = {
+ codeActionProvider = {
+ codeActionKinds = {
+ '',
+ 'quickfix',
+ 'refactor.rewrite',
+ 'refactor.extract',
+ },
+ resolveProvider = false,
+ },
+ },
abortByFileUpdate = true,
function (params)
local core = require 'core.code-action'
@@ -757,6 +803,17 @@ m.register 'textDocument/codeAction' {
}
m.register 'workspace/executeCommand' {
+ capability = {
+ executeCommandProvider = {
+ commands = {
+ 'lua.removeSpace',
+ 'lua.solve',
+ 'lua.jsonToLua',
+ 'lua.setConfig',
+ 'lua.autoRequire',
+ },
+ },
+ },
---@async
function (params)
local command = params.command:gsub(':.+', '')
@@ -780,6 +837,9 @@ m.register 'workspace/executeCommand' {
}
m.register 'workspace/symbol' {
+ capability = {
+ workspaceSymbolProvider = true,
+ },
abortByFileUpdate = true,
---@async
function (params)
@@ -826,7 +886,29 @@ m.register 'textDocument/semanticTokens/full' {
end
}
+local function toArray(map)
+ local array = {}
+ for k in pairs(map) do
+ array[#array+1] = k
+ end
+ table.sort(array, function (a, b)
+ return map[a] < map[b]
+ end)
+ return array
+end
+
+
m.register 'textDocument/semanticTokens/range' {
+ capability = {
+ semanticTokensProvider = {
+ legend = {
+ tokenTypes = toArray(define.TokenTypes),
+ tokenModifiers = toArray(define.TokenModifiers),
+ },
+ range = true,
+ full = false,
+ },
+ },
---@async
function (params)
log.debug('textDocument/semanticTokens/range')
@@ -843,11 +925,14 @@ m.register 'textDocument/semanticTokens/range' {
}
m.register 'textDocument/foldingRange' {
- abortByFileUpdate = true,
+ capability = {
+ foldingRangeProvider = true,
+ },
---@async
function (params)
local core = require 'core.folding'
local uri = files.getRealUri(params.textDocument.uri)
+ workspace.awaitReady(uri)
if not files.exists(uri) then
return nil
end
@@ -915,6 +1000,10 @@ m.register '$/status/click' {
}
m.register 'textDocument/formatting' {
+ capability = {
+ documentFormattingProvider = true,
+ },
+ preview = true,
---@async
function(params)
local uri = files.getRealUri(params.textDocument.uri)
@@ -923,11 +1012,15 @@ m.register 'textDocument/formatting' {
return nil
end
+ if not config.get(uri, 'Lua.format.enable') then
+ return nil
+ end
+
local pformatting = require 'provider.formatting'
pformatting.updateConfig(uri)
local core = require 'core.formatting'
- local edits = core(uri)
+ local edits = core(uri, params.options)
if not edits or #edits == 0 then
return nil
end
@@ -945,6 +1038,10 @@ m.register 'textDocument/formatting' {
}
m.register 'textDocument/rangeFormatting' {
+ capability = {
+ documentRangeFormattingProvider = true,
+ },
+ preview = true,
---@async
function(params)
local uri = files.getRealUri(params.textDocument.uri)
@@ -953,11 +1050,15 @@ m.register 'textDocument/rangeFormatting' {
return nil
end
+ if not config.get(uri, 'Lua.format.enable') then
+ return nil
+ end
+
local pformatting = require 'provider.formatting'
pformatting.updateConfig(uri)
local core = require 'core.rangeformatting'
- local edits = core(uri, params.range)
+ local edits = core(uri, params.range, params.options)
if not edits or #edits == 0 then
return nil
end
@@ -975,6 +1076,12 @@ m.register 'textDocument/rangeFormatting' {
}
m.register 'textDocument/onTypeFormatting' {
+ capability = {
+ documentOnTypeFormattingProvider = {
+ firstTriggerCharacter = '\n',
+ moreTriggerCharacter = nil, -- string[]
+ },
+ },
abortByFileUpdate = true,
---@async
function (params)
diff --git a/script/service/telemetry.lua b/script/service/telemetry.lua
index 94335fb9..2d956ed0 100644
--- a/script/service/telemetry.lua
+++ b/script/service/telemetry.lua
@@ -59,12 +59,29 @@ local function pushVersion(link)
))
end
+local function occlusionPath(str)
+ return str:gsub('(%s*)([^:"\'\r\n]+)', function (left, chunk)
+ if not chunk:find '[/\\]' then
+ return
+ end
+ local newStr, count = chunk:gsub('.+([/\\]script[/\\])', '***%1')
+ if count > 0 then
+ return left .. newStr
+ elseif chunk:sub(1, 1) == '\\'
+ or chunk:sub(1, 1) == '/'
+ or chunk:sub(1, 3) == '...' then
+ return left .. '***'
+ end
+ end)
+end
+
local function pushErrorLog(link)
- if not log.firstError then
+ local err = log.firstError
+ if not err then
return
end
- local err = log.firstError
log.firstError = nil
+ err = occlusionPath(err)
send(link, string.pack('zzzz'
, 'error'
, token
@@ -78,7 +95,7 @@ local isValid = false
timer.wait(5, function ()
timer.loop(300, function ()
- if not isValid then
+ if isValid ~= true then
return
end
local suc, link = pcall(net.connect, 'tcp', 'moe-moe.love', 11577)
@@ -97,7 +114,7 @@ timer.wait(5, function ()
end
end)()
timer.loop(1, function ()
- if not isValid then
+ if isValid ~= true then
return
end
net.update()
@@ -107,7 +124,9 @@ end)
local m = {}
function m.updateConfig()
- isValid = config.get(nil, 'Lua.telemetry.enable')
+ local enable = config.get(nil, 'Lua.telemetry.enable')
+ assert(enable == true or enable == false or enable == nil)
+ isValid = enable
if isValid == false then
return
end
diff --git a/script/vm/getDocs.lua b/script/vm/getDocs.lua
index d13878e6..4204d785 100644
--- a/script/vm/getDocs.lua
+++ b/script/vm/getDocs.lua
@@ -10,6 +10,9 @@ local define = require 'proto.define'
---@param name? string
---@return parser.object[]
function vm.getDocDefines(uri, name)
+ if type(name) ~= 'string' then
+ return {}
+ end
local cache = vm.getCache 'getDocDefines'
if cache[name] then
return cache[name]
diff --git a/script/workspace/require-path.lua b/script/workspace/require-path.lua
index f0a75eb1..56c94424 100644
--- a/script/workspace/require-path.lua
+++ b/script/workspace/require-path.lua
@@ -148,6 +148,9 @@ end
local function removeVisiblePath(uri)
local path = furi.decode(uri)
path = workspace.normalize(path)
+ if not path then
+ return
+ end
for _, scp in ipairs(workspace.folders) do
scp:get('visiblePath')[path] = nil
---@type collector
diff --git a/script/workspace/workspace.lua b/script/workspace/workspace.lua
index cb8bd68b..80df7d9c 100644
--- a/script/workspace/workspace.lua
+++ b/script/workspace/workspace.lua
@@ -234,6 +234,7 @@ end
---@async
function m.awaitLoadFile(uri)
+ m.awaitReady(uri)
local scp = scope.getScope(uri)
local ld <close> = loading.create(scp)
local native = m.getNativeMatcher(scp)
diff --git a/tools/love-api.lua b/tools/love-api.lua
index 8b7ba346..5b3c754b 100644
--- a/tools/love-api.lua
+++ b/tools/love-api.lua
@@ -80,12 +80,25 @@ local function buildSuper(tp)
return (': %s'):format(table.concat(parents, ', '))
end
-local function buildDescription(desc)
+local function buildMD(desc)
+ return desc:gsub('([\r\n])', '%1---')
+ :gsub('%. ', '.\n---\n---')
+end
+
+local function buildDescription(desc, notes)
+ local lines = {}
if desc then
- return ('---\n---%s\n---'):format(desc:gsub('([\r\n])', '%1---'))
- else
- return nil
+ lines[#lines+1] = '---'
+ lines[#lines+1] = '---' .. buildMD(desc)
+ lines[#lines+1] = '---'
+ end
+ if notes then
+ lines[#lines+1] = '---'
+ lines[#lines+1] = '---### NOTE:'
+ lines[#lines+1] = '---' .. buildMD(notes)
+ lines[#lines+1] = '---'
end
+ return table.concat(lines, '\n')
end
local function buildDocFunc(variant, overload)
@@ -124,7 +137,7 @@ end
local function buildFunction(func, node, typeName)
local text = {}
- text[#text+1] = buildDescription(func.description)
+ text[#text+1] = buildDescription(func.description, func.notes)
for i = 2, #func.variants do
local variant = func.variants[i]
text[#text+1] = ('---@overload %s'):format(buildDocFunc(variant, typeName))
@@ -167,7 +180,7 @@ local function buildFile(class, defs)
if defs.version then
text[#text+1] = ('-- version: %s'):format(defs.version)
end
- text[#text+1] = buildDescription(defs.description)
+ text[#text+1] = buildDescription(defs.description, defs.notes)
text[#text+1] = ('---@class %s'):format(class)
text[#text+1] = ('%s = {}'):format(class)
@@ -179,7 +192,7 @@ local function buildFile(class, defs)
for _, tp in ipairs(defs.types or {}) do
local mark = {}
text[#text+1] = ''
- text[#text+1] = buildDescription(tp.description)
+ text[#text+1] = buildDescription(tp.description, tp.notes)
text[#text+1] = ('---@class %s%s'):format(getTypeName(tp.name), buildSuper(tp))
text[#text+1] = ('local %s = {}'):format(tp.name)
for _, func in ipairs(tp.functions or {}) do
@@ -193,16 +206,16 @@ local function buildFile(class, defs)
for _, cb in ipairs(defs.callbacks or {}) do
text[#text+1] = ''
- text[#text+1] = buildDescription(cb.description)
+ text[#text+1] = buildDescription(cb.description, cb.notes)
text[#text+1] = ('---@alias %s %s'):format(getTypeName(cb.name), buildMultiDocFunc(cb))
end
for _, enum in ipairs(defs.enums or {}) do
text[#text+1] = ''
- text[#text+1] = buildDescription(enum.description)
+ text[#text+1] = buildDescription(enum.description, enum.notes)
text[#text+1] = ('---@alias %s'):format(getTypeName(enum.name))
for _, constant in ipairs(enum.constants) do
- text[#text+1] = buildDescription(constant.description)
+ text[#text+1] = buildDescription(constant.description, constant.notes)
text[#text+1] = ([[---| '%s']]):format(('%q'):format(constant.name):gsub("'", "\\'"))
end
end
diff --git a/tools/lovr-api.lua b/tools/lovr-api.lua
index 834c3e39..ca7c414e 100644
--- a/tools/lovr-api.lua
+++ b/tools/lovr-api.lua
@@ -84,12 +84,25 @@ local function buildSuper(tp)
return (': %s'):format(table.concat(parents, ', '))
end
-local function buildDescription(desc)
+local function buildMD(desc)
+ return desc:gsub('([\r\n])', '%1---')
+ :gsub('%. ', '.\n---\n---')
+end
+
+local function buildDescription(desc, notes)
+ local lines = {}
if desc then
- return ('---\n---%s\n---'):format(desc:gsub('([\r\n])', '%1---'))
- else
- return nil
+ lines[#lines+1] = '---'
+ lines[#lines+1] = '---' .. buildMD(desc)
+ lines[#lines+1] = '---'
+ end
+ if notes then
+ lines[#lines+1] = '---'
+ lines[#lines+1] = '---### NOTE:'
+ lines[#lines+1] = '---' .. buildMD(notes)
+ lines[#lines+1] = '---'
end
+ return table.concat(lines, '\n')
end
local function buildDocFunc(variant, overload)
@@ -128,7 +141,7 @@ end
local function buildFunction(func, typeName)
local text = {}
- text[#text+1] = buildDescription(func.description)
+ text[#text+1] = buildDescription(func.description, func.notes)
for i = 2, #func.variants do
local variant = func.variants[i]
text[#text+1] = ('---@overload %s'):format(buildDocFunc(variant, typeName))
@@ -168,7 +181,7 @@ local function buildFile(defs)
text[#text+1] = '---@meta'
text[#text+1] = ''
- text[#text+1] = buildDescription(defs.description)
+ text[#text+1] = buildDescription(defs.description, defs.notes)
text[#text+1] = ('---@class %s'):format(class)
text[#text+1] = ('%s = {}'):format(class)
@@ -180,7 +193,7 @@ local function buildFile(defs)
for _, obj in ipairs(defs.objects or {}) do
local mark = {}
text[#text+1] = ''
- text[#text+1] = buildDescription(obj.description)
+ text[#text+1] = buildDescription(obj.description, obj.notes)
text[#text+1] = ('---@class %s%s'):format(getTypeName(obj.name), buildSuper(obj))
text[#text+1] = ('local %s = {}'):format(obj.name)
for _, func in ipairs(obj.methods or {}) do
@@ -194,10 +207,10 @@ local function buildFile(defs)
for _, enum in ipairs(defs.enums or {}) do
text[#text+1] = ''
- text[#text+1] = buildDescription(enum.description)
+ text[#text+1] = buildDescription(enum.description, enum.notes)
text[#text+1] = ('---@alias %s'):format(getTypeName(enum.name))
for _, constant in ipairs(enum.values) do
- text[#text+1] = buildDescription(constant.description)
+ text[#text+1] = buildDescription(constant.description, constant.notes)
text[#text+1] = ([[---| '%s']]):format(('%q'):format(constant.name):gsub("'", "\\'"))
end
end
@@ -220,7 +233,7 @@ local function buildCallback(defs)
for _, cb in ipairs(defs.callbacks or {}) do
text[#text+1] = ''
- text[#text+1] = buildDescription(cb.description)
+ text[#text+1] = buildDescription(cb.description, cb.notes)
text[#text+1] = ('---@type %s'):format(buildMultiDocFunc(cb))
text[#text+1] = ('%s = nil'):format(cb.key)
end