From fc0dde1d05afefb372e03e5706a06f8afbe1d87a Mon Sep 17 00:00:00 2001 From: chrisgregan Date: Wed, 13 Apr 2016 12:05:58 +0100 Subject: [PATCH] Tidied up ExecuteLua initialisation --- .../Fungus/Lua/Scripts/Commands/ExecuteLua.cs | 44 +++++++++++-------- 1 file changed, 26 insertions(+), 18 deletions(-) diff --git a/Assets/Fungus/Lua/Scripts/Commands/ExecuteLua.cs b/Assets/Fungus/Lua/Scripts/Commands/ExecuteLua.cs index 3e1c447c..ff8c2033 100644 --- a/Assets/Fungus/Lua/Scripts/Commands/ExecuteLua.cs +++ b/Assets/Fungus/Lua/Scripts/Commands/ExecuteLua.cs @@ -30,33 +30,41 @@ namespace Fungus protected string friendlyName = ""; + protected bool initialised ; + protected virtual void Start() { + InitExecuteLua(); + } + + /// + /// Initialises the Lua environment and compiles the Lua string for execution later on. + /// + protected virtual void InitExecuteLua() + { + if (initialised) + { + return; + } + // Cache a descriptive name to use in Lua error messages friendlyName = gameObject.name + "." + parentBlock.blockName + "." + "ExecuteLua #" + commandIndex.ToString(); - if (luaEnvironment == null) - { - luaEnvironment = LuaEnvironment.GetLua(); - } - } + if (luaEnvironment == null) + { + luaEnvironment = LuaEnvironment.GetLua(); + } + + initialised = true; + } public override void OnEnter() { - // This command could be executed from the Start of another component, so we - // need to check the Lua Environment here and in Start. - if (luaEnvironment == null) - { - luaEnvironment = LuaEnvironment.GetLua(); - } - - if (luaEnvironment == null) - { - Debug.LogError("No Lua Environment found"); - Continue(); - return; - } + InitExecuteLua(); + // Note: We can't pre compile the Lua script in this command because we want to + // support variable substitution in the Lua string. + // If this is too slow, consider using a LuaScript object and calling OnExecute() on it instead. string subbed = GetFlowchart().SubstituteVariables(luaScript); luaEnvironment.DoLuaString(subbed, friendlyName, runAsCoroutine, (returnValue) => {