Better locking

Re-implemented Lock using lua scripting to provide a considerably simpler and safer mechanism for locking.

Also add some tests to the locking implementation.

Let's get lua_support merged and released as well!