pub type CFunction = extern "C-unwind" fn(lua: LuaState) -> AmountReturned;Expand description
A safe function using the C ABI that Lua can call.
This type is technically a subset of lua_CFunction, as it only allows safe functions.
Different methods will use either lua_CFunction or CFunction based on if they work with only safe functions or not.
It is always safe to convert a CFunction into a lua_CFunction (see SafeFn::to_raw).
§Protocol
To communicate properly, Lua expects CFunctions to follow a specific protocol:
Arguments passed to the CFunction are located in the stack (index 1 contains the first argument, etc.),
thus LuaState::get_top can be used to know the number of arguments received.
Values to return to the caller should be pushed onto the stack (first value is returned first, etc.),
using the returned AmountReturned to specify how many values were returned.
AmountReturned can be obtained manually using LuaState::return_any or automatically for simple values
using the designated methods (LuaState::return_number, LuaState::return_string, etc…).
§Examples
use low_luajit::{LuaState, AmountReturned};
extern "C-unwind" fn sum(mut lua: LuaState) -> AmountReturned {
// Retrieve the arguments, asserting that they exist and are of the correct type.
let x = lua.check_number(1);
let y = lua.check_number(2);
// Push the value to return and return 1 since we're only returning a single value.
lua.push_number(x + y);
lua.return_any(1)
}Alternatively, using LuaState::return_number:
use low_luajit::{LuaState, AmountReturned};
extern "C-unwind" fn sum(lua: LuaState) -> AmountReturned {
// Retrieve the arguments, asserting that they exist and are of the correct type.
let x = lua.check_number(1);
let y = lua.check_number(2);
// Just return the number (does the same as the other example, just more concise).
lua.return_number(x + y)
}