// Adapted from the Unity Test Tools project (MIT license) // https://bitbucket.org/Unity-Technologies/unitytesttools/src/a30d562427e9/Assets/UnityTestTools/ using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using UnityEngine; using MoonSharp.Interpreter; using Debug = UnityEngine.Debug; using Object = UnityEngine.Object; namespace Fungus { public class LuaScript : MonoBehaviour { /// /// The Lua Environment to use when executing Lua script. /// [Tooltip("The Lua Environment to use when executing Lua script.")] public LuaEnvironment luaEnvironment; /// /// Lua script file to execute. /// [Tooltip("Lua script file to execute.")] public TextAsset luaFile; /// /// Lua script to execute. /// [Tooltip("Lua script to execute.")] [TextArea(5, 50)] public string luaScript = ""; /// /// Run the script as a Lua coroutine so execution can be yielded for asynchronous operations. /// [Tooltip("Run the script as a Lua coroutine so execution can be yielded for asynchronous operations.")] public bool runAsCoroutine = true; protected string friendlyName = ""; protected bool initialised; // Recursively build the full hierarchy path to this game object private static string GetPath(Transform current) { if (current.parent == null) { return current.name; } return GetPath(current.parent) + "." + current.name; } public void Start() { InitLuaScript(); } protected virtual void InitLuaScript() { if (initialised) { return; } if (luaEnvironment == null) { // Create a Lua Environment if none exists yet luaEnvironment = LuaEnvironment.GetLua(); } if (luaEnvironment == null) { Debug.LogError("No Lua Environment found"); return; } // Ensure the LuaEnvironment is initialized before trying to execute code luaEnvironment.InitEnvironment(); // Cache a descriptive name to use in Lua error messages friendlyName = GetPath(transform) + ".LuaScript"; initialised = true; } /// /// Execute the Lua script. /// This is the function to call if you want to trigger execution from an external script. /// public virtual void OnExecute() { // Make sure the environment is initialised before executing InitLuaScript(); if (luaEnvironment == null) { Debug.LogWarning("No Lua Environment found"); } else { // Ensure the Lua Environment is initialised first. luaEnvironment.InitEnvironment(); string s = ""; if (luaFile != null) { s = luaFile.text; } else if (luaScript.Length > 0) { s = luaScript; } luaEnvironment.DoLuaString(s, friendlyName, runAsCoroutine); } } } }