extern crate lua;
extern crate libc;
use lua::ffi::lua_State;
use lua::{State, Function};
use libc::c_int;
struct Point2D {
x: i64,
y: i64
}
impl Point2D {
fn new(x: i64, y: i64) -> Point2D {
return Point2D {
x: x, y: y
};
}
#[allow(non_snake_case)]
unsafe extern "C" fn lua_new(L: *mut lua_State) -> c_int {
let mut state = State::from_ptr(L);
let x = state.opt_integer(1, 0);
let y = state.opt_integer(2, 0);
*state.new_userdata_typed::<Point2D>() = Point2D::new(x, y);
state.set_metatable_from_registry("Point2D");
1
}
#[allow(non_snake_case)]
unsafe extern "C" fn lua_x(L: *mut lua_State) -> c_int {
let mut state = State::from_ptr(L);
let point = state.check_userdata(1, "Point2D") as *mut Point2D;
state.push_integer((*point).x);
1
}
#[allow(non_snake_case)]
unsafe extern "C" fn lua_y(L: *mut lua_State) -> c_int {
let mut state = State::from_ptr(L);
let point = state.check_userdata(1, "Point2D") as *mut Point2D;
state.push_integer((*point).y);
1
}
}
const POINT2D_LIB: [(&'static str, Function); 3] = [
("new", Some(Point2D::lua_new)),
("x", Some(Point2D::lua_x)),
("y", Some(Point2D::lua_y))
];
fn main() {
let mut state = lua::State::new();
state.open_libs();
state.new_table();
state.set_fns(&POINT2D_LIB, 0);
state.push_value(-1);
state.set_global("Point2D");
state.new_metatable("Point2D");
state.push_value(-2);
state.set_field(-2, "__index");
state.pop(2);
state.do_string("local p = Point2D.new(12, 34)
print(p:x(), p:y())");
}