// Copyright (c) Pixel Crushers. All rights reserved. using UnityEngine; namespace PixelCrushers.DialogueSystem { /// /// Lua expression changed delegate. /// public delegate void LuaChangedDelegate(LuaWatchItem luaWatchItem, Lua.Result newValue); /// /// Watch item for Lua observers. This allows the observer to be notified when a Lua value changes. /// public class LuaWatchItem { /// /// The lua expression to watch. /// public string luaExpression { get; set; } /// @cond FOR_V1_COMPATIBILITY public string LuaExpression { get { return luaExpression; } set { luaExpression = value; } } /// @endcond /// /// The current value of the expression. /// private string m_currentValue; /// /// Delegate to call when the expression changes. /// private event LuaChangedDelegate luaChanged; public static string LuaExpressionWithReturn(string luaExpression) { return luaExpression.StartsWith("return ") ? luaExpression : ("return " + luaExpression); } /// /// Initializes a new instance of the class. /// /// /// Lua expression to watch. /// /// /// Delegate to call when the expression changes. /// public LuaWatchItem(string luaExpression, LuaChangedDelegate luaChangedHandler) { this.luaExpression = LuaExpressionWithReturn(luaExpression); this.m_currentValue = Lua.Run(this.luaExpression).asString; this.luaChanged = luaChangedHandler; } /// /// Checks if the watch item matches a specified luaExpression and luaChangedHandler. /// /// /// The lua expression. /// /// /// The notification delegate. /// public bool Matches(string luaExpression, LuaChangedDelegate luaChangedHandler) { return (luaChangedHandler == luaChanged) && string.Equals(luaExpression, this.luaExpression); } /// /// Checks the watch item and calls the delegate if the Lua expression changed. /// public void Check() { Lua.Result result = Lua.Run(luaExpression); string newValue = result.asString; if (!string.Equals(m_currentValue, newValue)) { m_currentValue = newValue; if (luaChanged != null) luaChanged(this, result); } } } }