Skip to main content

lua_std/
lib.rs

1//! Reference for the Lua 5.5 standard library.
2//!
3//! Lua is a dynamically typed language: values carry types, variables do not.
4//! Every value belongs to one of the basic types documented here — [`nil`],
5//! [`boolean`], [`number`], [`string`], [`table`], [`function`], [`userdata`]
6//! and [`thread`].
7//!
8//! The standard library provides a set of global functions (listed below),
9//! functions attached to the [`string`] and [`table`] types, and the
10//! [`math`], [`os`], [`io`], [`coroutine`] and [`utf8`] libraries.
11//!
12//! The behaviour of operators on values can be customised through
13//! *metatables* — see the Metatables section below.
14//!
15//! ```lua
16//! print("hello, world")
17//! ```
18//!
19//! ---
20//!
21//! Lua and its logo are from [Lua.org](https://www.lua.org/) — logo
22//! © 1998 Lua.org, graphic design by Alexandre Nakonechnyj.
23
24#![cfg_attr(doc, feature(doc_cfg))]
25#![doc(html_logo_url = "/lua-std-doc/lua.png")]
26#![doc(html_favicon_url = "/lua-std-doc/lua.png")]
27#![allow(non_camel_case_types)]
28#![allow(non_upper_case_globals)]
29#![allow(unused_variables)]
30
31mod metatable;
32mod number_;
33mod string_;
34mod table_;
35
36#[cfg(feature = "extended")]
37mod extended;
38#[cfg(feature = "extended")]
39pub use extended::*;
40
41pub use metatable::*;
42pub use number_::*;
43pub use string_::*;
44pub use table_::*;
45
46pub mod coroutine;
47pub mod io;
48pub mod math;
49pub mod os;
50pub mod utf8;
51
52/// The type of the absence of a value.
53///
54/// `nil` has a single value, also called **nil**, whose main property is to
55/// be different from every other value. It usually represents a missing or
56/// deleted value: assigning `nil` to a table field removes that field, and
57/// reading a variable that was never assigned yields `nil`.
58///
59/// In a condition, `nil` (together with `false`) counts as false; every
60/// other value counts as true.
61pub struct nil;
62
63/// The type of the truth values **true** and **false**.
64///
65/// Only `false` and [`nil`] are treated as false in conditions; everything
66/// else — including `0` and the empty string — is true.
67pub struct boolean;
68
69/// The type of Lua and C functions.
70///
71/// Functions are first-class values: they can be stored in variables and
72/// tables, passed as arguments, and returned from other functions.
73///
74/// A variadic function collects its extra arguments in a *vararg
75/// table*, whose field `n` holds their count. Since Lua 5.5 that table
76/// can be given a name after the three dots, becoming a read-only local:
77///
78/// ```lua
79/// local function f(...args)
80///   print(args.n, args[1])
81/// end
82/// f("a", "b")    --> 2   a
83/// ```
84///
85/// ```lua
86/// local greet = function(name)
87///   return "hello, " .. name
88/// end
89/// print(greet("world"))
90/// ```
91pub struct function;
92
93/// The type of arbitrary C data.
94///
95/// A userdata value carries a block of raw memory managed by the host
96/// program. Userdata values cannot be created or modified in Lua, only
97/// through the C API; they typically represent objects belonging to the
98/// host application or to C libraries.
99pub struct userdata;
100
101/// The type of independent threads of execution, used to implement
102/// coroutines.
103///
104/// Threads are created with [`coroutine::create`] and are not related to
105/// operating-system threads. See the [`coroutine`] library.
106pub struct thread;
107
108/// Marker for a variable number of values of type `T` (`...` in Lua).
109/// Rendered by custom.html as `...name: T`.
110#[doc(hidden)]
111pub struct Repeatable<T>(core::marker::PhantomData<T>);
112
113/// Marker for a value that may be `T` or nil.
114/// Rendered by custom.html as `T | nil`.
115#[doc(hidden)]
116#[allow(non_camel_case_types)]
117pub struct option<T>(core::marker::PhantomData<T>);
118
119/// Stands for a value of any type.
120///
121/// This is a documentation convention, not a real Lua type: where a
122/// signature says `any`, the function accepts (or may return) a value of
123/// any of the basic types — [`nil`], [`boolean`], [`number`],
124/// [`string`], [`table`], [`function`], [`userdata`] or [`thread`].
125///
126/// Use [`type`](crate::type()) to find out at run time which type a
127/// value actually has:
128///
129/// ```lua
130/// print(type("hi"), type(42), type({}))    --> string   number   table
131/// ```
132pub struct any;
133
134/// A global variable that holds the global environment itself.
135///
136/// Lua does not use this value; changing it does not affect any
137/// environment. Setting a field in `_G` is the same as assigning to a
138/// global variable.
139///
140/// # Examples
141///
142/// ```lua
143/// x = 10
144/// print(_G.x)    --> 10
145/// _G.y = 20
146/// print(y)       --> 20
147/// ```
148pub static _G: table = table;
149
150/// A global variable containing the running Lua version, as a string —
151/// currently `"Lua 5.5"`.
152///
153/// # Examples
154///
155/// ```lua
156/// print(_VERSION)    --> Lua 5.5
157/// ```
158pub static _VERSION: string = string;
159
160/// Raises an error if the value of its argument `v` is false (i.e. `nil`
161/// or `false`); otherwise, returns all its arguments. On error, `message`
162/// is used as the error object; when absent, it defaults to
163/// `"assertion failed!"`.
164///
165/// ```lua
166/// local f = assert(io.open("config.txt"))  -- error if the open failed
167/// ```
168pub fn assert(v: any, message: option<string>) -> Repeatable<any> {
169    todo!()
170}
171
172/// A generic interface to the garbage collector. Performs different jobs
173/// according to `opt`: `"collect"` runs a full collection cycle (the
174/// default), `"stop"` and `"restart"` pause and resume the collector,
175/// `"count"` returns the total memory in use by Lua in kilobytes,
176/// `"step"` performs an incremental step, `"isrunning"` tells whether
177/// the collector is stopped, and `"incremental"` / `"generational"`
178/// select the collector mode.
179///
180/// **Changed in Lua 5.5:** collector parameters are read and set through
181/// the new `"param"` option — `collectgarbage("param", name [, value])`
182/// — where `name` is one of `"pause"`, `"stepmul"`, `"stepsize"` (for
183/// the incremental collector) or `"minormul"`, `"minormajor"`,
184/// `"majorminor"` (for the generational collector). In 5.5 major
185/// collections of the generational collector are done incrementally.
186///
187/// # Examples
188///
189/// ```lua
190/// print(collectgarbage("count"))   --> 24.35  (kilobytes in use)
191/// collectgarbage()                 -- run a full collection cycle
192/// ```
193pub fn collectgarbage(opt: option<string>) -> any {
194    todo!()
195}
196
197/// Opens the named file and executes its contents as a Lua chunk. When
198/// called without arguments, executes the contents of the standard input.
199/// Returns all values returned by the chunk. In case of errors, `dofile`
200/// propagates the error to its caller: it does not run in protected mode.
201///
202/// # Examples
203///
204/// ```lua
205/// dofile("config.lua")     -- run config.lua in the current environment
206/// ```
207pub fn dofile(filename: option<string>) -> Repeatable<any> {
208    todo!()
209}
210
211/// Raises an error with `message` as the error object. This function never
212/// returns.
213///
214/// Usually, `error` adds some information about the error position at the
215/// beginning of the message, if the message is a string. The `level`
216/// argument specifies how to get the error position: with level 1 (the
217/// default), the error position is where `error` was called; level 2
218/// points the error to where the function that called `error` was called;
219/// level 0 avoids adding position information.
220///
221/// # Examples
222///
223/// ```lua
224/// local ok, err = pcall(function()
225///   error("something broke")
226/// end)
227/// print(ok, err)    --> false   input:2: something broke
228/// error({ code = 42 })         -- any value can be an error object
229/// ```
230pub fn error(message: any, level: option<number>) {
231    todo!()
232}
233
234/// If `object` does not have a metatable, returns `nil`. Otherwise, if the
235/// metatable has a `__metatable` field, returns the associated value.
236/// Otherwise, returns the metatable of the given object.
237///
238/// # Examples
239///
240/// ```lua
241/// print(getmetatable({}))            --> nil
242/// print(getmetatable(""))            --> table: 0x...  (the string metatable)
243/// local t = setmetatable({}, { __metatable = "locked" })
244/// print(getmetatable(t))             --> locked
245/// ```
246pub fn getmetatable(object: any) -> option<table> {
247    todo!()
248}
249
250/// Returns three values (an iterator function, `t`, and 0) so that the
251/// construction
252///
253/// ```lua
254/// for i, v in ipairs(t) do body end
255/// ```
256///
257/// will iterate over the key–value pairs `(1, t[1])`, `(2, t[2])`, ...,
258/// up to the first absent index.
259pub fn ipairs(t: table) -> (function, table, number) {
260    todo!()
261}
262
263/// Loads a chunk. If `chunk` is a string, the chunk is that string; if it
264/// is a function, `load` calls it repeatedly to get the chunk pieces. If
265/// there are no syntactic errors, returns the compiled chunk as a
266/// function; otherwise, returns `nil` plus the error message.
267///
268/// `chunkname` is used in error messages and debug information; `mode`
269/// controls whether the chunk can be text or binary; `env` sets the first
270/// upvalue (`_ENV`) of the resulting function.
271///
272/// # Examples
273///
274/// ```lua
275/// local f = load("return 1 + 2")
276/// print(f())                         --> 3
277/// local bad, msg = load("return +")
278/// print(bad, msg)                    --> nil   [string "return +"]:1: unexpected symbol
279/// ```
280pub fn load(
281    chunk: any,
282    chunkname: option<string>,
283    mode: option<string>,
284    env: option<any>,
285) -> option<function> {
286    todo!()
287}
288
289/// Allows a program to traverse all fields of a table. Its first argument
290/// is a table and its second argument is an index in this table. A call
291/// returns the next index of the table and its associated value; when
292/// called with `nil` as its second argument, returns an initial index and
293/// its associated value. When called with the last index, or with `nil`
294/// in an empty table, returns `nil`.
295///
296/// The order in which the indices are enumerated is not specified, *even
297/// for numeric indices*.
298///
299/// # Examples
300///
301/// ```lua
302/// local t = { a = 1 }
303/// print(next(t))         --> a   1
304/// print(next(t, "a"))    --> nil       (no more fields)
305/// print(next({}))        --> nil       (empty table)
306/// ```
307pub fn next(t: table, index: option<any>) -> (any, any) {
308    todo!()
309}
310
311/// Returns three values (the [`next`] function, the table `t`, and `nil`)
312/// so that the construction
313///
314/// ```lua
315/// for k, v in pairs(t) do body end
316/// ```
317///
318/// will iterate over all key–value pairs of the table.
319///
320/// If `t` has a metamethod `__pairs`, calls it with `t` as argument and
321/// returns the first three results from the call instead.
322pub fn pairs(t: table) -> (function, table, nil) {
323    todo!()
324}
325
326/// Calls the function `f` with the given arguments in *protected mode*:
327/// errors inside `f` are not propagated. Returns a status code (a
328/// boolean) followed, on success, by all results of the call, or, on
329/// failure, by the error object.
330///
331/// ```lua
332/// local ok, err = pcall(function() error("boom") end)
333/// print(ok, err)  --> false   input:1: boom
334/// ```
335pub fn pcall(f: function, args: Repeatable<any>) -> (boolean, Repeatable<any>) {
336    todo!()
337}
338
339/// Receives any number of arguments and prints their values to the
340/// standard output, converting each to a string following the same rules
341/// as [`tostring()`], separated by tabs and followed by a newline.
342///
343/// `print` is meant for quick debugging, not for formatted output — for
344/// that, use [`string::format`] and [`io::write`].
345///
346/// # Examples
347///
348/// ```lua
349/// print("x", 42, true)      --> x   42   true
350/// print()                   --> (just a newline)
351/// ```
352pub fn print<T: tostring>(values: Repeatable<T>) {
353    todo!()
354}
355
356/// Checks whether `v1` is equal to `v2`, without invoking the `__eq`
357/// metamethod. Returns a boolean.
358///
359/// # Examples
360///
361/// ```lua
362/// local mt = { __eq = function() return true end }
363/// local a, b = setmetatable({}, mt), setmetatable({}, mt)
364/// print(a == b)           --> true    (uses __eq)
365/// print(rawequal(a, b))   --> false   (different tables)
366/// print(rawequal(a, a))   --> true
367/// ```
368pub fn rawequal(v1: any, v2: any) -> boolean {
369    todo!()
370}
371
372/// Gets the real value of `t[index]`, without using the `__index`
373/// metamethod. `t` must be a table.
374///
375/// # Examples
376///
377/// ```lua
378/// local t = setmetatable({}, { __index = function() return "fallback" end })
379/// print(t.missing)             --> fallback
380/// print(rawget(t, "missing"))  --> nil
381/// ```
382pub fn rawget(t: table, index: any) -> any {
383    todo!()
384}
385
386/// Returns the length of the object `v`, which must be a table or a
387/// string, without invoking the `__len` metamethod.
388///
389/// # Examples
390///
391/// ```lua
392/// local t = setmetatable({1, 2, 3}, { __len = function() return 42 end })
393/// print(#t)          --> 42
394/// print(rawlen(t))   --> 3
395/// print(rawlen("hello"))   --> 5
396/// ```
397pub fn rawlen<T: length>(v: T) -> number {
398    todo!()
399}
400
401/// Sets the real value of `t[index]` to `value`, without using the
402/// `__newindex` metamethod. `t` must be a table, `index` any value
403/// different from `nil` and NaN. Returns `t`.
404///
405/// # Examples
406///
407/// ```lua
408/// local t = setmetatable({}, { __newindex = function() error("read-only") end })
409/// rawset(t, "k", 1)      -- bypasses __newindex
410/// print(t.k)             --> 1
411/// ```
412pub fn rawset(t: table, index: any, value: any) -> table {
413    todo!()
414}
415
416/// Loads the given module. Starts by looking into the `package.loaded`
417/// table to determine whether `modname` is already loaded; if so, returns
418/// the stored value. Otherwise, finds a loader for the module by
419/// consulting the searchers in `package.searchers`, runs it, and caches
420/// its result in `package.loaded[modname]`.
421///
422/// # Examples
423///
424/// ```lua
425/// local socket = require("socket")
426/// print(require("socket") == socket)    --> true  (cached in package.loaded)
427/// ```
428pub fn require(modname: string) -> any {
429    todo!()
430}
431
432/// If `index` is a number, returns all arguments after argument number
433/// `index`; a negative number indexes from the end (−1 is the last
434/// argument). Otherwise, `index` must be the string `"#"`, and `select`
435/// returns the total number of extra arguments it received.
436///
437/// # Examples
438///
439/// ```lua
440/// print(select("#", "a", "b", "c"))    --> 3
441/// print(select(2, "a", "b", "c"))      --> b   c
442/// print(select(-1, "a", "b", "c"))     --> c
443/// ```
444pub fn select(index: any, values: Repeatable<any>) -> Repeatable<any> {
445    todo!()
446}
447
448/// Sets the metatable for the given table. If `metatable` is `nil`,
449/// removes the metatable of the table. If the original metatable has a
450/// `__metatable` field, raises an error.
451///
452/// Returns `t`. (To change the metatable of other types from Lua code,
453/// you must use the debug library.)
454///
455/// # Examples
456///
457/// ```lua
458/// local parent = { greet = function() print("hi") end }
459/// local child = setmetatable({}, { __index = parent })
460/// child.greet()    --> hi   (found through __index)
461/// ```
462pub fn setmetatable(t: table, metatable: option<table>) -> table {
463    todo!()
464}
465
466/// When called with no `base`, tries to convert its argument to a number.
467/// If the argument is already a number or a string convertible to a
468/// number, returns that number; otherwise, returns `nil`.
469///
470/// When called with a `base`, `v` must be a string to be interpreted as an
471/// integer numeral in that base (from 2 to 36, letters `A`–`Z` standing
472/// for 10–35).
473///
474/// # Examples
475///
476/// ```lua
477/// print(tonumber("42"))        --> 42
478/// print(tonumber("0x1F"))      --> 31
479/// print(tonumber("3.7e2"))     --> 370.0
480/// print(tonumber("ff", 16))    --> 255
481/// print(tonumber("hello"))     --> nil
482/// ```
483pub fn tonumber(v: any, base: option<number>) -> option<number> {
484    todo!()
485}
486
487/// Receives a value of any type and converts it to a string in a
488/// human-readable format.
489///
490/// If the metatable of `v` has a `__tostring` field, `tostring` calls the
491/// corresponding value with `v` as argument and uses the result. If it
492/// has a `__name` field with a string value, that string is used in the
493/// result. For full control of how numbers are converted, use
494/// [`string::format`].
495///
496/// # Examples
497///
498/// ```lua
499/// print(tostring(42))       --> 42
500/// print(tostring(nil))      --> nil
501/// local pt = setmetatable({}, { __tostring = function() return "Point" end })
502/// print(tostring(pt))       --> Point
503/// ```
504pub fn tostring<T: tostring>(v: T) -> string {
505    todo!()
506}
507
508/// Returns the type of its only argument, coded as a string. The possible
509/// results are `"nil"`, `"boolean"`, `"number"`, `"string"`, `"table"`,
510/// `"function"`, `"userdata"` and `"thread"`.
511///
512/// # Examples
513///
514/// ```lua
515/// print(type(nil))         --> nil
516/// print(type(42))          --> number
517/// print(type("hi"))        --> string
518/// print(type({}))          --> table
519/// print(type(print))       --> function
520/// ```
521pub fn r#type(v: any) -> string {
522    todo!()
523}
524
525/// Like [`pcall`], but sets `msgh` as a message handler: in case of error,
526/// `msgh` is called with the error object before the stack unwinds, and
527/// its return value becomes the error object returned by `xpcall`.
528///
529/// # Examples
530///
531/// ```lua
532/// local ok, err = xpcall(function()
533///   error("boom")
534/// end, function(e)
535///   return "handled: " .. e
536/// end)
537/// print(ok, err)    --> false   handled: input:2: boom
538/// ```
539pub fn xpcall(f: function, msgh: function, args: Repeatable<any>) -> (boolean, Repeatable<any>) {
540    todo!()
541}