Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- namespace Example
- {
- /// <summary>
- /// Full Lua state
- /// </summary>
- public class LuaState : Lua
- {
- /// <summary>
- /// Lock which covers Lua function lookups and execution
- /// </summary>
- readonly object _lock = new object();
- /// <summary>
- /// Initialize an independent threadsafe Lua state with a preset namespace.
- /// </summary>
- public LuaState ()
- {
- lock (_lock) // Try to keep any Lua functions from being called via C# until the namespace is set.
- {
- // Environment setup - The lock isn't really needed here, but it's a good idea as long as you're not blocking for too long (ie, if you're paranoid about other threads trying to access the state before it's fully initialized)
- }
- }
- /// <summary>
- /// Threadsafe return of the LuaFunction object for a named function.
- /// Fails silently.
- /// </summary>
- /// <param name="name">Name/location of function</param>
- /// <returns>LuaFunction or null</returns>
- new public LuaFunction GetFunction(string name)
- {
- lock (_lock)
- {
- try
- {
- return base.GetFunction(name);
- }
- catch (Exception)
- {
- return null;
- }
- }
- }
- /// <summary>
- /// Threadsafe Lua function call with optional args.
- /// </summary>
- /// <param name="name">Name/location of function</param>
- /// <param name="args">List of args to pass</param>
- public void Call(string name, params object[] args)
- {
- lock (_lock)
- {
- Log.getInstance();
- LuaFunction f = GetFunction(name);
- if (f == null)
- {
- Log.log(1, "Unable to find Lua function '" + name + "'. This is probably harmless.");
- }
- else
- {
- try
- {
- f.Call(args);
- }
- catch (Exception e)
- {
- Log.log(4, e.Message);
- }
- }
- }
- }
- /// <summary>
- /// Lock-and-get shortcut for threaded reads.
- /// </summary>
- /// <param name="k">path within Lua state</param>
- /// <returns></returns>
- public object Get(string k)
- {
- lock (_lock)
- {
- return this[k];
- }
- }
- /// <summary>
- /// Lock-and-set shortcut for threaded writes.
- /// </summary>
- /// <param name="k">path within Lua state</param>
- /// <param name="v">value to write</param>
- public void Set(string k, object v)
- {
- lock (_lock)
- {
- this[k] = v;
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement