lua_shared/
lib.rs

1#![allow(non_camel_case_types)]
2
3use std::{ffi::c_void, ptr::null_mut};
4
5mod loadx;
6pub use loadx::loadx;
7
8mod dump;
9pub use dump::dump;
10
11#[macro_export]
12macro_rules! pop {
13    ($L:expr, $n:expr) => {
14        $crate::settop($L, -($n) - 1)
15    };
16}
17
18#[macro_export]
19macro_rules! getglobal {
20    ($L:expr, $s:expr) => {
21        $crate::getfield($L, $crate::GLOBALSINDEX, $s)
22    };
23}
24
25#[macro_export]
26macro_rules! setglobal {
27    ($L:expr, $s:expr) => {
28        $crate::setfield($L, $crate::GLOBALSINDEX, $s)
29    };
30}
31
32#[macro_export]
33macro_rules! upvalueindex {
34    ($index:expr) => {
35        $crate::GLOBALSINDEX - ($index)
36    };
37}
38
39#[macro_export]
40macro_rules! cstr {
41    ($str:expr) => {
42        concat!($str, "\0").as_ptr() as _
43    };
44}
45
46pub static REGISTRYINDEX: i32 = -10000;
47pub static ENVIRONINDEX: i32 = -10001;
48pub static GLOBALSINDEX: i32 = -10002;
49
50pub type lua_State = *mut c_void;
51pub type lua_CFunction = unsafe extern "C" fn(state: lua_State) -> i32;
52pub type lua_Reader =
53    unsafe extern "C" fn(state: lua_State, userdata: *mut c_void, size: &mut usize) -> *const u8;
54pub type lua_Writer = unsafe extern "C" fn(
55    state: lua_State,
56    data: *const u8,
57    size: usize,
58    userdata: *mut c_void,
59) -> i32;
60pub type Result = std::result::Result<i32, Box<dyn std::error::Error>>;
61
62#[repr(C)]
63#[derive(Debug)]
64pub enum Status {
65    Ok = 0,
66    Yield = 1,
67    RuntimeError = 2,
68    SyntaxError = 3,
69    MemoryError = 4,
70    Error = 5,
71}
72
73#[derive(Debug)]
74pub enum LError {
75    RuntimeError,
76    SyntaxError(String),
77    MemoryError(String),
78    DumpError(i32),
79}
80
81pub enum LoadMode {
82    Any,
83    Binary,
84    Text,
85}
86
87// LOL
88// This piece of "code" greatly reduces shit that needed to be in `build.rs`
89#[cfg(all(target_os = "linux", target_pointer_width = "32"))]
90#[link(name = ":lua_shared_srv.so", kind = "dylib")]
91extern "C" {}
92
93#[cfg(all(target_os = "linux", target_pointer_width = "64"))]
94#[link(name = ":lua_shared.so", kind = "dylib")]
95extern "C" {}
96
97#[cfg(target_os = "windows")]
98#[link(name = "lua_shared", kind = "dylib")]
99extern "C" {}
100
101extern "C" {
102    // state manipulation
103
104    /// Creates a new Lua state.
105    /// It calls `lua_newstate` with an allocator based on the standard C realloc function and then sets a panic function that prints an error message to the standard error output in case of fatal errors.
106    ///
107    /// Returns the new state, or `NULL` if there is a memory allocation error.
108    #[link_name = "luaL_newstate"]
109    pub fn newstate() -> lua_State;
110    /// Destroys all objects in the given Lua state (calling the corresponding garbage-collection metamethods, if any) and frees all dynamic memory used by this state.
111    /// In several platforms, you may not need to call this function, because all resources are naturally released when the host program ends.
112    /// On the other hand, long-running programs that create multiple states, such as daemons or web servers, will probably need to close states as soon as they are not needed.
113    #[link_name = "lua_close"]
114    pub fn close(state: lua_State);
115    /// Creates a new thread, pushes it on the stack, and returns a pointer to a [`lua_State`] that represents this new thread.
116    /// The new thread returned by this function shares with the original thread its global environment, but has an independent execution stack.
117    /// There is no explicit function to close or to destroy a thread. Threads are subject to garbage collection, like any Lua object.
118    #[link_name = "lua_newthread"]
119    pub fn newthread(state: lua_State) -> lua_State;
120
121    // basic stack manipulation
122
123    /// Returns the index of the top element in the stack. Because indices start at 1, this result is equal to the number of elements in the stack; in particular, 0 means an empty stack.
124    #[link_name = "lua_gettop"]
125    pub fn gettop(state: lua_State) -> i32;
126    /// Accepts any index, or 0, and sets the stack top to this index.
127    /// If the new top is larger than the old one, then the new elements are filled with **nil**. If index is 0, then all stack elements are removed.
128    #[link_name = "lua_settop"]
129    pub fn settop(state: lua_State, index: i32);
130    /// Pushes a copy of the element at the given index onto the stack.
131    #[link_name = "lua_pushvalue"]
132    pub fn pushvalue(state: lua_State, index: i32);
133    /// Removes the element at the given valid index, shifting down the elements above this index to fill the gap.
134    /// This function cannot be called with a pseudo-index, because a pseudo-index is not an actual stack position.
135    #[link_name = "lua_remove"]
136    pub fn remove(state: lua_State, index: i32);
137    /// Moves the top element into the given valid index, shifting up the elements above this index to open space.
138    /// This function cannot be called with a pseudo-index, because a pseudo-index is not an actual stack position.
139    #[link_name = "lua_insert"]
140    pub fn insert(state: lua_State, index: i32);
141    /// Moves the top element into the given valid index without shifting any element (therefore replacing the value at that given index), and then pops the top element.
142    #[link_name = "lua_replace"]
143    pub fn replace(state: lua_State, index: i32);
144    /// Ensures that the stack has space for at least n extra slots (that is, that you can safely push up to n values into it).
145    /// It returns false if it cannot fulfill the request, either because it would cause the stack to be larger than a fixed maximum size (typically at least several thousand elements) or because it cannot allocate memory for the extra space.
146    /// This function never shrinks the stack; if the stack already has space for the extra slots, it is left unchanged.
147    #[link_name = "lua_checkstack"]
148    pub fn checkstack(state: lua_State, size: i32) -> bool;
149
150    // access functions (stack -> C)
151
152    /// Returns `true` if the value at the given index is a number or a string convertible to a number, and `false` otherwise.
153    #[link_name = "lua_isnumber"]
154    pub fn isnumber(state: lua_State, index: i32) -> bool;
155    /// Returns `true` if the value at the given index is a string or a number (which is always convertible to a string), and `false` otherwise.
156    #[link_name = "lua_isstring"]
157    pub fn isstring(state: lua_State, index: i32) -> bool;
158    /// Returns `true` if the value at the given index is a C function, and `true` otherwise.
159    #[link_name = "lua_iscfunction"]
160    pub fn iscfunction(state: lua_State, index: i32) -> bool;
161    /// Returns `true` if the value at the given index is a userdata (either full or light), and `false` otherwise.
162    #[link_name = "lua_isuserdata"]
163    pub fn isuserdata(state: lua_State, index: i32) -> bool;
164    /// Returns the type of the value in the given valid index, or `LUA_TNONE` for a non-valid (but acceptable) index.
165    /// The types returned by [`get_type`] (`lua_type`) are coded by the following constants defined in lua.h: `LUA_TNIL` (0), `LUA_TNUMBER, LUA_TBOOLEAN, LUA_TSTRING, LUA_TTABLE, LUA_TFUNCTION, LUA_TUSERDATA, LUA_TTHREAD,` and `LUA_TLIGHTUSERDATA`.
166    #[link_name = "lua_type"]
167    pub fn get_type(state: lua_State, index: i32) -> i32;
168    /// Returns the name of the type encoded by the value tp, which must be one the values returned by [`get_type`] (`lua_type`).
169    #[link_name = "lua_typename"]
170    pub fn typename(state: lua_State, index: i32) -> *const u8;
171
172    /// Returns `true` if the two values in acceptable indices `index1` and `index2` are equal, following the semantics of the Lua `==` operator (that is, may call metamethods).
173    /// Otherwise returns `false`. Also returns `false` if any of the indices is non valid.
174    #[link_name = "lua_equal"]
175    pub fn equal(state: lua_State, index1: i32, index2: i32) -> bool;
176    /// Returns `true` if the two values in acceptable indices `index1` and `index2` are primitively equal (that is, without calling metamethods). Otherwise returns `false`.
177    /// Also returns `false` if any of the indices are non valid.
178    #[link_name = "lua_rawequal"]
179    pub fn rawequal(state: lua_State, index1: i32, index2: i32) -> bool;
180    /// Returns `true` if the value at acceptable index `index1` is smaller than the value at acceptable index `index2`, following the semantics of the Lua `<` operator (that is, may call metamethods).
181    /// Otherwise returns `false`. Also returns 0 if any of the indices is non valid.
182    #[link_name = "lua_lessthan"]
183    pub fn lessthan(state: lua_State, index1: i32, index2: i32) -> bool;
184
185    /// Converts the Lua value at the given acceptable index to the C type `lua_Number` (see [lua_Number](https://www.lua.org/manual/5.1/manual.html#lua_Number)).
186    /// The Lua value must be a number or a string convertible to a number (see [§2.2.1](https://www.lua.org/manual/5.1/manual.html#2.2.1)); otherwise, [`tonumber`] (`lua_tonumber`) returns `0`.
187    #[link_name = "lua_tonumber"]
188    pub fn tonumber(state: lua_State, index: i32) -> f64;
189
190    /// Converts the Lua value at the given acceptable index to the signed integral type [lua_Integer](https://www.lua.org/manual/5.1/manual.html#lua_Integer).
191    /// The Lua value must be a number or a string convertible to a number (see [§2.2.1](https://www.lua.org/manual/5.1/manual.html#2.2.1)); otherwise, [`tointeger`] (`lua_tointeger`) returns 0.
192    #[link_name = "lua_tointeger"]
193    pub fn tointeger(state: lua_State, index: i32) -> isize;
194    /// Converts the Lua value at the given acceptable index to a C boolean value (0 or 1).
195    /// Like all tests in Lua, [`toboolean`] (`lua_toboolean`) returns `true` for any Lua value different from **false** and **nil**; otherwise it returns `false`.
196    /// It also returns `false` when called with a non-valid index.
197    #[link_name = "lua_toboolean"]
198    pub fn toboolean(state: lua_State, index: i32) -> bool;
199    /// Converts the Lua value at the given acceptable index to a C string.
200    /// If `len` is not `NULL`, it also sets `*len` with the string length.
201    /// The Lua value must be a string or a number; otherwise, the function returns `NULL`.
202    /// If the value is a number, then [`tolstring`] also changes the actual value in the stack to a string.
203    #[link_name = "lua_tolstring"]
204    pub fn tolstring(state: lua_State, index: i32, len: &mut usize) -> *const u8;
205    /// Returns the "length" of the value at the given acceptable index: for strings, this is the string length; for tables, this is the result of the length operator (`'#'`); for userdata, this is the size of the block of memory allocated for the userdata; for other values, it is 0.
206    #[link_name = "lua_objlen"]
207    pub fn objlen(state: lua_State, index: i32) -> usize;
208    /// Converts a value at the given acceptable index to a C function. That value must be a C function; otherwise, returns `NULL`.
209    #[link_name = "lua_tocfunction"]
210    pub fn tocfunction(state: lua_State, index: i32) -> Option<lua_CFunction>;
211    /// If the value at the given acceptable index is a full userdata, returns its block address. If the value is a light userdata, returns its pointer. Otherwise, returns `NULL`.
212    #[link_name = "lua_touserdata"]
213    pub fn touserdata(state: lua_State, index: i32) -> *mut c_void;
214    /// Converts the value at the given acceptable index to a Lua thread (represented as [`lua_State`]). This value must be a thread; otherwise, the function returns `NULL`.
215    #[link_name = "lua_tothread"]
216    pub fn tothread(state: lua_State, index: i32) -> lua_State;
217    /// Converts the value at the given acceptable index to a generic C pointer (`void*`).
218    /// The value can be a userdata, a table, a thread, or a function; otherwise, [`topointer`] (`lua_topointer`) returns `NULL`.
219    /// Different objects will give different pointers. There is no way to convert the pointer back to its original value.
220    ///
221    /// Typically this function is used only for debug information.
222    #[link_name = "lua_topointer"]
223    pub fn topointer(state: lua_State, index: i32) -> *const c_void;
224
225    // push functions (C -> stack)
226
227    /// Pushes a nil value onto the stack.
228    #[link_name = "lua_pushnil"]
229    pub fn pushnil(state: lua_State);
230    /// Pushes a number with value `number` onto the stack.
231    #[link_name = "lua_pushnumber"]
232    pub fn pushnumber(state: lua_State, number: f64);
233    /// Pushes a number with value `number` onto the stack.
234    #[link_name = "lua_pushinteger"]
235    pub fn pushinteger(state: lua_State, integer: isize);
236    /// Pushes the string pointed to by `str` with size `len` onto the stack.
237    /// Lua makes (or reuses) an internal copy of the given string, so the memory at `str` can be freed or reused immediately after the function returns.
238    /// The string can contain embedded zeros.
239    #[link_name = "lua_pushlstring"]
240    pub fn pushlstring(state: lua_State, str: *const u8, len: usize);
241    /// Pushes the zero-terminated string pointed to by `str` onto the stack. Lua makes (or reuses) an internal copy of the given string, so the memory at `str` can be freed or reused immediately after the function returns.
242    /// The string cannot contain embedded zeros; it is assumed to end at the first zero.
243    #[link_name = "lua_pushstring"]
244    pub fn pushstring(state: lua_State, str: *const u8);
245    /// Pushes a new C closure onto the stack.
246    ///
247    /// When a C function is created, it is possible to associate some values with it, thus creating a C closure (see [§3.4](https://www.lua.org/manual/5.1/manual.html#3.4)); these values are then accessible to the function whenever it is called.
248    /// To associate values with a C function, first these values should be pushed onto the stack (when there are multiple values, the first value is pushed first).
249    /// Then [`pushcclosure`] (`lua_pushcclosure`)  is called to create and push the C function onto the stack, with the argument n telling how many values should be associated with the function.
250    /// [`pushcclosure`] (`lua_pushcclosure`) also pops these values from the stack.
251    ///
252    /// The maximum value for `upvalues` is 255.
253    #[link_name = "lua_pushcclosure"]
254    pub fn pushcclosure(state: lua_State, func: lua_CFunction, upvalues: i32);
255    /// Pushes a boolean value with value `bool` onto the stack.
256    #[link_name = "lua_pushboolean"]
257    pub fn pushboolean(state: lua_State, bool: i32);
258    /// Pushes a light userdata onto the stack.
259    ///
260    /// Userdata represent C values in Lua
261    /// A _light userdata_ represents a pointer.
262    /// It is a value (like a number): you do not create it, it has no individual metatable, and it is not collected (as it was never created).
263    /// A light userdata is equal to "any" light userdata with the same C address.
264    #[link_name = "lua_pushlightuserdata"]
265    pub fn pushlightuserdata(state: lua_State, ptr: *const c_void);
266    /// Pushes the thread represented by `state` onto the stack. Returns 1 if this thread is the main thread of its state.
267    #[link_name = "lua_pushthread"]
268    pub fn pushthread(state: lua_State) -> i32;
269
270    // get functions (Lua -> stack)
271
272    /// Pushes onto the stack the value `t[k]`, where `t` is the value at the given valid index and `k` is the value at the top of the stack.
273    ///
274    /// This function pops the key from the stack (putting the resulting value in its place).
275    /// As in Lua, this function may trigger a metamethod for the "index" event (see [§2.8](https://www.lua.org/manual/5.1/manual.html#2.8)).
276    #[link_name = "lua_gettable"]
277    pub fn gettable(state: lua_State, index: i32);
278    /// Pushes onto the stack the value `t[k]`, where `t` is the value at the given valid index. As in Lua, this function may trigger a metamethod for the "index" event (see [§2.8](https://www.lua.org/manual/5.1/manual.html#2.8)).
279    #[link_name = "lua_getfield"]
280    pub fn getfield(state: lua_State, index: i32, str: *const u8);
281    /// Similar to [`gettable`] (`lua_gettable`), but does a raw access (i.e., without metamethods).
282    #[link_name = "lua_rawget"]
283    pub fn rawget(state: lua_State, index: i32);
284    /// Pushes onto the stack the value `t[n]`, where `t` is the value at the given valid index. The access is raw; that is, it does not invoke metamethods.
285    #[link_name = "lua_rawgeti"]
286    pub fn rawgeti(state: lua_State, index: i32, slot: i32);
287    /// Creates a new empty table and pushes it onto the stack.
288    /// The new table has space pre-allocated for `array` array elements and `hash` non-array elements.
289    /// This pre-allocation is useful when you know exactly how many elements the table will have.
290    #[link_name = "lua_createtable"]
291    pub fn createtable(state: lua_State, array: i32, hash: i32);
292    /// This function allocates a new block of memory with the given size, pushes onto the stack a new full userdata with the block address, and returns this address.
293    ///
294    /// Userdata represent C values in Lua.
295    /// A _full userdata_ represents a block of memory.
296    /// It is an object (like a table): you must create it, it can have its own metatable, and you can detect when it is being collected.
297    /// A full userdata is only equal to itself (under raw equality).
298    ///
299    /// When Lua collects a full userdata with a [`__gc`](https://www.lua.org/manual/5.1/manual.html#2.10.1) metamethod, Lua calls the metamethod and marks the userdata as finalized.
300    /// When this userdata is collected again then Lua frees its corresponding memory.
301    #[link_name = "lua_newuserdata"]
302    pub fn newuserdata(state: lua_State, size: usize) -> *mut c_void;
303    /// Pushes onto the stack the metatable of the value at the given acceptable index. If the index is not valid, or if the value does not have a metatable, the function returns 0 and pushes nothing on the stack.
304    #[link_name = "lua_getmetatable"]
305    pub fn getmetatable(state: lua_State, index: i32) -> i32;
306    /// Pushes onto the stack the environment table of the value at the given index.
307    #[link_name = "lua_getfenv"]
308    pub fn getfenv(state: lua_State, index: i32);
309
310    // set functions (stack -> Lua)
311
312    /// Does the equivalent to `t[k] = v`, where `t` is the value at the given valid index, `v` is the value at the top of the stack, and `k` is the value just below the top.
313    ///
314    /// This function pops both the key and the value from the stack. As in Lua, this function may trigger a metamethod for the "newindex" event (see [§2.8](https://www.lua.org/manual/5.1/manual.html#2.8)).
315    #[link_name = "lua_settable"]
316    pub fn settable(state: lua_State, index: i32);
317    /// Does the equivalent to `t[k] = v`, where `t` is the value at the given valid index and `v` is the value at the top of the stack.
318    ///
319    /// This function pops the value from the stack. As in Lua, this function may trigger a metamethod for the "newindex" event (see [§2.8](https://www.lua.org/manual/5.1/manual.html#2.8)).
320    #[link_name = "lua_setfield"]
321    pub fn setfield(state: lua_State, index: i32, str: *const u8);
322    /// Similar to [`settable`] (`lua_settable`), but does a raw assignment (i.e., without metamethods).
323    #[link_name = "lua_rawset"]
324    pub fn rawset(state: lua_State, index: i32);
325    /// Does the equivalent of `t[n] = v`, where `t` is the value at the given valid index and `v` is the value at the top of the stack.
326    ///
327    /// This function pops the value from the stack. The assignment is raw; that is, it does not invoke metamethods.
328    #[link_name = "lua_rawseti"]
329    pub fn rawseti(state: lua_State, index: i32, slot: i32);
330    /// Pops a table from the stack and sets it as the new metatable for the value at the given acceptable index.
331    #[link_name = "lua_setmetatable"]
332    pub fn setmetatable(state: lua_State, index: i32) -> i32;
333    /// Pops a table from the stack and sets it as the new environment for the value at the given index. If the value at the given index is neither a function nor a thread nor a userdata, [`setfenv`] (`lua_setfenv`) returns 0. Otherwise it returns 1.
334    #[link_name = "lua_setfenv"]
335    pub fn setfenv(state: lua_State, index: i32) -> i32;
336
337    // `load' and `call' functions (load and run Lua code)
338
339    /// Calls a function.
340    ///
341    /// To call a function you must use the following protocol: first, the function to be called is pushed onto the stack; then, the arguments to the function are pushed in direct order; that is, the first argument is pushed first.
342    /// Finally you call [`call`] (`lua_call`); `nargs` is the number of arguments that you pushed onto the stack.
343    /// All arguments and the function value are popped from the stack when the function is called.
344    /// The function results are pushed onto the stack when the function returns.
345    /// The number of results is adjusted to `nrets`, unless `nrets` is `LUA_MULTRET`.
346    /// In this case, _all_ results from the function are pushed.
347    /// Lua takes care that the returned values fit into the stack space.
348    /// The function results are pushed onto the stack in direct order (the first result is pushed first), so that after the call the last result is on the top of the stack.
349    ///
350    /// Any error inside the called function is propagated upwards (with a `longjmp`).
351    #[link_name = "lua_call"]
352    pub fn call(state: lua_State, nargs: i32, nrets: i32);
353    /// Calls a function in protected mode.
354    ///
355    /// Both nargs and nresults have the same meaning as in [`call`] (`lua_call`).
356    /// If there are no errors during the call, [`pcall`] (`lua_pcall`) behaves exactly like [`call`] (`lua_call`).
357    /// However, if there is any error, [`pcall`] (`lua_pcall`) catches it, pushes a single value on the stack (the error message), and returns an error code.
358    /// Like [`call`] (`lua_call`), [`pcall`] (`lua_pcall`) always removes the function and its arguments from the stack.
359    ///
360    /// If `errfunc` is 0, then the error message returned on the stack is exactly the original error message.
361    /// Otherwise, `errfunc` is the stack index of an _error handler function_. (In the current implementation, this index cannot be a pseudo-index.)
362    /// In case of runtime errors, this function will be called with the error message and its return value will be the message returned on the stack by [`pcall`] (`lua_pcall`).
363    #[link_name = "lua_pcall"]
364    pub fn pcall(state: lua_State, nargs: i32, nrets: i32, errfunc: i32) -> Status;
365    fn lua_loadx(
366        state: lua_State,
367        reader: lua_Reader,
368        userdata: *mut c_void,
369        chunk_name: *const u8,
370        mode: *const u8,
371    ) -> Status;
372    fn lua_dump(state: lua_State, writer: lua_Writer, userdata: *mut c_void) -> i32;
373
374    // miscellaneous functions
375
376    /// Generates a Lua error. The error message (which can actually be a Lua value of any type) must be on the stack top. This function does a long jump, and therefore never returns. (see [`luaL_error`](https://www.lua.org/manual/5.1/manual.html#luaL_error)).
377    #[link_name = "lua_error"]
378    pub fn error(state: lua_State) -> !;
379    // #[link_name = "lua_next"]
380    // fn lua_next(state: lua_State, index: i32) -> i32;
381    // #[link_name = "lua_concat"]
382    // fn lua_concat(state: lua_State, index: i32);
383
384    // lauxlib
385
386    /// Checks whether the function argument `index` is a string and returns this string; if `length` is not NULL fills `*length` with the string's length.
387    ///
388    /// This function uses [`tolstring`] (`lua_tolstring`) to get its result, so all conversions and caveats of that function apply here.
389    #[link_name = "luaL_checklstring"]
390    pub fn Lchecklstring(state: lua_State, index: i32, length: &mut usize) -> *const u8;
391    /// If the function argument `index` is a string, returns this string. If this argument is absent or is **nil**, returns `default`. Otherwise, raises an error.
392    ///
393    /// If `length` is not `NULL`, fills the position `*length` with the results's length.
394    #[link_name = "luaL_optlstring"]
395    pub fn Loptlstring(
396        state: lua_State,
397        index: i32,
398        default: *const u8,
399        length: &mut usize,
400    ) -> *const u8;
401    /// Checks whether the function argument `index` is a number and returns this number.
402    #[link_name = "luaL_checknumber"]
403    pub fn Lchecknumber(state: lua_State, index: i32) -> f64;
404    /// If the function argument `index` is a number, returns this number. If this argument is absent or is **nil**, returns `default`. Otherwise, raises an error.
405    #[link_name = "luaL_optnumber"]
406    pub fn Loptnumber(state: lua_State, index: i32, default: f64) -> f64;
407    /// Checks whether the function argument `index` is a number and returns this number cast to a [`lua_Integer`](https://www.lua.org/manual/5.1/manual.html#lua_Integer).
408    #[link_name = "luaL_checkinteger"]
409    pub fn Lcheckinteger(state: lua_State, index: i32) -> isize;
410    /// If the function argument `index` is a number, returns this number cast to a [`lua_Integer`](https://www.lua.org/manual/5.1/manual.html#lua_Integer).
411    /// If this argument is absent or is **nil**, returns `default`. Otherwise, raises an error.
412    #[link_name = "luaL_optinteger"]
413    pub fn Loptinteger(state: lua_State, index: i32, default: isize) -> isize;
414    /// Grows the stack size to `top + size` elements, raising an error if the stack cannot grow to that size. `msg` is an additional text to go into the error message.
415    #[link_name = "luaL_checkstack"]
416    pub fn Lcheckstack(state: lua_State, size: i32, msg: *const u8);
417    /// Checks whether the function argument `index` has type `typ`. See [`lua_type`](https://www.lua.org/manual/5.1/manual.html#lua_type) for the encoding of types for `typ`.
418    #[link_name = "luaL_checktype"]
419    pub fn Lchecktype(state: lua_State, index: i32, typ: i32);
420    /// Checks whether the function has an argument of any type (including **nil**) at position `index`.
421    #[link_name = "luaL_checkany"]
422    pub fn Lcheckany(state: lua_State, index: i32);
423    /// Raises an error with the following message, where `func` is retrieved from the call stack
424    #[link_name = "luaL_argerror"]
425    pub fn Largerror(state: lua_State, index: i32, msg: *const u8) -> !;
426
427    /// If the registry already has the key `type_name`, returns `false`. Otherwise, creates a new table to be used as a metatable for userdata, adds it to the registry with key `type_name`, and returns `true`.
428    ///
429    /// In both cases pushes onto the stack the final value associated with `type_name` in the registry.
430    #[link_name = "luaL_newmetatable"]
431    pub fn Lnewmetatable(state: lua_State, type_name: *const u8) -> bool;
432    /// Checks whether the function argument `index` is a userdata of the type `type_name` (see [`Lnewmetatable`]).
433    #[link_name = "luaL_checkudata"]
434    pub fn Lcheckudata(state: lua_State, index: i32, type_name: *const u8) -> *mut c_void;
435
436    /// Pushes onto the stack a string identifying the current position of the control at level `level` in the call stack. Typically this string has the following format:
437    /// ```text
438    ///     chunkname:currentline:
439    /// ```
440    /// Level 0 is the running function, level 1 is the function that called the running function, etc.
441    ///
442    /// This function is used to build a prefix for error messages.
443    #[link_name = "luaL_where"]
444    pub fn Lpush_where(state: lua_State, level: i32);
445    /// Raises an error. The error message format is given by `fmt` plus any extra arguments, following the same rules of [`lua_pushfstring`](https://www.lua.org/manual/5.1/manual.html#lua_pushfstring).
446    /// It also adds at the beginning of the message the file name and the line number where the error occurred, if this information is available.
447    ///
448    /// This function never returns, but it is an idiom to use it in C functions as `return luaL_error(args)`.
449    #[link_name = "luaL_error"]
450    pub fn Lerror(state: lua_State, fmt: *const u8, ...) -> !;
451
452    /// Loads a buffer as a Lua chunk. This function uses [`lua_load`](https://www.lua.org/manual/5.1/manual.html#lua_load) to load the chunk in the buffer pointed to by `buffer` with size `size`.
453    ///
454    /// This function returns the same results as [`lua_load`](https://www.lua.org/manual/5.1/manual.html#lua_load). `name` is the chunk name, used for debug information and error messages. The string mode works as in function [`lua_load`](https://www.lua.org/manual/5.1/manual.html#lua_load).
455    #[link_name = "luaL_loadbufferx"]
456    pub fn Lloadbufferx(
457        state: lua_State,
458        buffer: *const u8,
459        size: usize,
460        name: *const u8,
461        mode: *const u8,
462    ) -> Status;
463
464    /// Opens all standard Lua libraries into the given state.
465    #[link_name = "luaL_openlibs"]
466    pub fn Lopenlibs(state: lua_State);
467
468    #[link_name = "luaopen_base"]
469    pub fn open_base(state: lua_State) -> i32;
470    #[link_name = "luaopen_package"]
471    pub fn open_package(state: lua_State) -> i32;
472    #[link_name = "luaopen_math"]
473    pub fn open_math(state: lua_State) -> i32;
474    #[link_name = "luaopen_bit"]
475    pub fn open_bit(state: lua_State) -> i32;
476    #[link_name = "luaopen_string"]
477    pub fn open_string(state: lua_State) -> i32;
478    #[link_name = "luaopen_table"]
479    pub fn open_table(state: lua_State) -> i32;
480    #[link_name = "luaopen_os"]
481    pub fn open_os(state: lua_State) -> i32;
482    #[link_name = "luaopen_debug"]
483    pub fn open_debug(state: lua_State) -> i32;
484    #[link_name = "luaopen_jit"]
485    pub fn open_jit(state: lua_State) -> i32;
486}
487
488/// Pushes rust function/closure to lua stack.
489/// # Example
490/// ```
491/// let state = newstate();
492/// createtable(state, 0, 2);
493/// pushfunction(state, |_| {
494///     println!("Hello there!");
495///     Ok(0)
496/// });
497/// setfield(state, -2, cstr!("test_immutable_closure"));
498/// fn test_function(state: lua_State) -> Result {
499///     println!("Hello there, but from functuin, I guess.");
500///     Ok(0)
501/// }
502/// pushfunction(state, test_function);
503/// setfield(state, -2, cstr!("test_immutable_function"));
504///
505/// let mut counter = 0;
506/// pushfunction_mut(state, move |_| {
507///     println!("Here is yout counter!: {}", counter);
508///     pushinteger(state, counter);
509///     counter += 1;
510///     Ok(1)
511/// });
512/// setfield(state, -2, cstr!("test_mutable_closure"));
513/// setfield(state, GLOBALSINDEX, cstr!("tests"));
514/// ```
515pub unsafe fn pushfunction<FUNC>(state: lua_State, callback: FUNC)
516where
517    FUNC: 'static + FnMut(lua_State) -> Result,
518{
519    unsafe extern "C" fn call_callback<FUNC>(state: lua_State) -> i32
520    where
521        FUNC: 'static + FnMut(lua_State) -> Result,
522    {
523        let callback_ptr = if std::mem::size_of::<FUNC>() > 0 {
524            touserdata(state, upvalueindex!(1))
525        } else {
526            null_mut()
527        };
528        match (&mut *callback_ptr.cast::<FUNC>())(state) {
529            Ok(nrets) => nrets,
530            Err(err) => {
531                let error_str = err.to_string();
532                std::mem::drop(err);
533                pushlstring(
534                    state,
535                    error_str.as_bytes().as_ptr(),
536                    error_str.as_bytes().len(),
537                );
538                std::mem::drop(error_str);
539                error(state);
540            }
541        }
542    }
543
544    if std::mem::size_of::<FUNC>() > 0 {
545        let udata_ptr = newuserdata(state, std::mem::size_of::<FUNC>()).cast::<FUNC>();
546        udata_ptr.write(callback);
547        unsafe extern "C" fn cleanup_callback<FUNC>(state: lua_State) -> i32
548        where
549            FUNC: 'static + FnMut(lua_State) -> Result,
550        {
551            touserdata(state, 1).cast::<FUNC>().drop_in_place();
552            0
553        }
554        createtable(state, 0, 1);
555        pushcclosure(state, cleanup_callback::<FUNC>, 0);
556        setfield(state, -2, cstr!("__gc"));
557        setmetatable(state, -2);
558        pushcclosure(state, call_callback::<FUNC>, 1);
559    } else {
560        pushcclosure(state, call_callback::<FUNC>, 0);
561    }
562}