extern crate lua;
extern crate libc;
use lua::ffi::lua_State;
use lua::{State, Function};
use libc::c_int;
struct VecWrapper {
data: Vec<i64>
}
impl VecWrapper {
fn new() -> VecWrapper {
VecWrapper {
data: Vec::new()
}
}
#[allow(non_snake_case)]
unsafe extern "C" fn lua_new(L: *mut lua_State) -> c_int {
let mut state = State::from_ptr(L);
let v: *mut VecWrapper = state.new_userdata_typed();
std::ptr::write(v, VecWrapper::new());
state.set_metatable_from_registry("VecWrapper");
1
}
#[allow(non_snake_case)]
unsafe extern "C" fn lua_get(L: *mut lua_State) -> c_int {
let mut state = State::from_ptr(L);
let v = state.check_userdata(1, "VecWrapper") as *mut VecWrapper;
let i = state.check_integer(2) as usize;
match (*v).data.get(i) {
Some(value) => state.push_integer(*value),
None => state.push_nil()
};
1
}
#[allow(non_snake_case)]
unsafe extern "C" fn lua_push(L: *mut lua_State) -> c_int {
let mut state = State::from_ptr(L);
let v = state.check_userdata(1, "VecWrapper") as *mut VecWrapper;
let i = state.check_integer(2);
(*v).data.push(i);
1
}
#[allow(non_snake_case)]
unsafe extern "C" fn lua_len(L: *mut lua_State) -> c_int {
let mut state = State::from_ptr(L);
let v = state.check_userdata(1, "VecWrapper") as *mut VecWrapper;
state.push_integer((*v).data.len() as i64);
1
}
#[allow(non_snake_case)]
unsafe extern "C" fn lua_gc(L: *mut lua_State) -> c_int {
let mut state = State::from_ptr(L);
let v = state.check_userdata(1, "VecWrapper") as *mut VecWrapper;
std::ptr::drop_in_place(v);
0
}
}
const VECWRAPPER_LIB: [(&'static str, Function); 4] = [
("new", Some(VecWrapper::lua_new)),
("get", Some(VecWrapper::lua_get)),
("push", Some(VecWrapper::lua_push)),
("len", Some(VecWrapper::lua_len))
];
fn main() {
let mut state = lua::State::new();
state.open_libs();
state.new_table();
state.set_fns(&VECWRAPPER_LIB, 0);
state.push_value(-1);
state.set_global("VecWrapper");
state.new_metatable("VecWrapper");
state.push_value(-2);
state.set_field(-2, "__index");
state.push_fn(Some(VecWrapper::lua_gc));
state.set_field(-2, "__gc");
state.pop(2);
state.do_string("local v = VecWrapper.new()
v:push(12)
v:push(34)
-- should print 2
print('length of vec is', v:len())
-- should print 12 34 nil
print(v:get(0), v:get(1), v:get(2))");
}