1

I am writing a program that uses hlua to call Lua code that pushes to a Vec. The problem is, I have multiple Lua methods that push to the same Vec. Here is a very simplified version of what I am trying to do:

let mut vec = Vec::new();
{
    let mut lua = Lua::new();

    // these functions do different things in my actual code
    lua.set("pushA", hlua::function1(|s: String| {
        vec.push(s);
    }));
    lua.set("pushB", hlua::function1(|s: String| {
        vec.push(s);
    }));

    lua.execute::<()>("...");
}

The compiler errors with this:

error[E0499]: cannot borrow `vec` as mutable more than once at a time
  --> src/main.rs:11:42
   |
10 |         lua.set("pushA", hlua::function1(|s: String| { vec.push(s); }));
   |                                          -----------   --- previous borrow occurs due to use of `vec` in closure
   |                                          |
   |                                          first mutable borrow occurs here
11 |         lua.set("pushB", hlua::function1(|s: String| { vec.push(s); }));
   |                                          ^^^^^^^^^^^   --- borrow occurs due to use of `vec` in closure
   |                                          |
   |                                          second mutable borrow occurs here
...
14 |     }
   |     - first borrow ends here

which I understand, but I can't come up with a solution to my problem where this would not occur in one way or another. I am very new with Rust, so this may be a dumb question.

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
rytone
  • 155
  • 2
  • 11
  • 2
    @Shepmaster Oh, huh. I somehow managed to look at every single one of those questions that didn't quite apply to my situation, and not the ones that answered my question. Sorry about that. Looks like `RefCell` is the solution to my problem – rytone Apr 22 '17 at 23:32
  • 1
    http://stackoverflow.com/questions/38027461/execute-callbacks-like-as-mutable-borrowing-from-cycle and http://stackoverflow.com/questions/43552480/whats-the-correct-way-to-implement-the-equivalent-of-multiple-mutable-statical helped. – rytone Apr 22 '17 at 23:37

0 Answers0