Type Alias tlua::ffi::lua_CFunction

source ·
pub type lua_CFunction = unsafe extern "C" fn(l: *mut lua_State) -> c_int;
Expand description

Type for C functions.

In order to communicate properly with Lua, a C function must use the following protocol, which defines the way parameters and results are passed: a C function receives its arguments from Lua in its stack in direct order (the first argument is pushed first). So, when the function starts, lua_gettop(L) returns the number of arguments received by the function. The first argument (if any) is at index 1 and its last argument is at index lua_gettop(L). To return values to Lua, a C function just pushes them onto the stack, in direct order (the first result is pushed first), and returns the number of results. Any other value in the stack below the results will be properly discarded by Lua. Like a Lua function, a C function called by Lua can also return many results.

As an example, the following function receives a variable number of numerical arguments and returns their average and sum:

use tlua::c_ptr;
use tlua::ffi::{
    lua_gettop, lua_isnumber, lua_pushstring, lua_error, lua_tonumber,
    lua_pushnumber, lua_State, lua_Number,
};
unsafe extern "C" fn foo(l: *mut lua_State) -> i32 {
    let n = lua_gettop(l);    /* number of arguments */
    let mut sum: lua_Number = 0.;
    let i: i32;
    for i in 1..=n {
        if !lua_isnumber(l, i) {
            lua_pushstring(l, c_ptr!("incorrect argument"));
            lua_error(l);
        }
        sum += lua_tonumber(l, i);
    }
    lua_pushnumber(l, sum / n as f64); /* first result */
    lua_pushnumber(l, sum);     /* second result */
    return 2;                   /* number of results */
}