tomassedovic / tcod-rs

Rust bindings for libtcod 1.6.3 (the Doryen library/roguelike toolkit)
Do What The F*ck You Want To Public License
229 stars 45 forks source link

Pass extra data to Bsp::traverse callback? #227

Open keisetsu opened 8 years ago

keisetsu commented 8 years ago

libtcod seems to have an argument for extra data to be passed to the traverse callback method (used in the python explanation of creating a map with bsp trees), and I see something for it in the c wrapper, but I don't see any way to use it. Is this possible, and if so, how?

zsparal commented 8 years ago

We are actually using the data argument to pass the closure itself. You should be able to capture any data you need, as shown in the BSP docs:

let mut counter = 0;
bsp.traverse(TraverseOrder::PreOrder, |node| {
    counter += 1;
    true
});

Here you can use counter as you would the data argument in the C API's case (only safer, because your code is still being checked by the borrow checker).

keisetsu commented 8 years ago

Thanks. I was having a problem using a mutable reference in a function call, but I think I can do something like this:

fn traverse_callback(node: &mut Bsp, map: &mut Map) -> bool {
    ...
    true
} 

let mut map: Map = vec![...];
let bsp: mut Bsp = Bsp::new_with_size(0, 0, 20, 20);
bsp.traverse(TraverseOrder::InvertedLevelOrder, |node| {
                 traverse_node(node, &mut floor);
    });

May be something to go in the documentation. This is probably obvious to experienced rust programmers, but I was expecting to be able to provide extra arguments, then provide a callback function instead of a closure.