Example #1
0
        public LuaScriptEngine(Game game) : base(game)
        {
            MoonSharp.Interpreter.Script.DefaultOptions.DebugPrint = text =>
            {
                Diagnostics.LuaScriptConsole._scriptConsoleTextAll =
                    string.Concat(Diagnostics.LuaScriptConsole._scriptConsoleTextAll, text, "\n");
            };

            MainScript = new MoonSharp.Interpreter.Script();

            FunctionInit();

            try
            {
                LuaCompatibility.Apply(MainScript);

                // Load scripts.lua file from file system or big file
                var filePath  = Path.Combine("Data", "Scripts", "scripts.lua");
                var fileEntry = Game.ContentManager.FileSystem.GetFile(filePath);
                if (fileEntry != null)
                {
                    Logger.Info($"Executing file {filePath}");
                    using var fileStream = fileEntry.Open();
                    MainScript.DoStream(fileStream);
                }
            }
            catch (Exception ex)
            {
                Logger.Error(ex, "Error while loading script file");
            }

            LuaEventHandlerInit();
        }
Example #2
0
 public Script(string script, string name)
 {
     FullPath  = String.Empty;
     Name      = name;
     Compiled  = new MoonSharp.Interpreter.Script(CoreModules.Preset_SoftSandbox);
     RawSource = script;
 }
Example #3
0
        public override void AddBindings(LuaEnvironment luaEnv)
        {
            if (!Init())
            {
                return;
            }

            MoonSharp.Interpreter.Script interpreter = luaEnv.Interpreter;
            Table globals = interpreter.Globals;

            if (globals == null)
            {
                Debug.LogError("Lua globals table is null");
                return;
            }

            // If the fungus global table is defined then add the store to it
            Table fungusTable = globals.Get("fungus").Table;

            if (fungusTable != null)
            {
                fungusTable["store"] = primeTable;
            }
            else
            {
                // Add the store as a global
                globals["store"] = primeTable;
            }
        }
Example #4
0
        public void LoadString(string code)
        {
            Lua = new MoonScript {
                Options = { CheckThreadAccess = false }
            };
            SetGlobals();

            Lua.DoString(code);

            if (!MemberExists(FpsNumberName, DataType.Number))
            {
                throw new Exception($"'{FpsNumberName}' number must be declared");
            }

            if (!MemberExists(DrawFunctionName, DataType.Function))
            {
                throw new Exception($"'{DrawFunctionName}' function must be declared");
            }

            if (Lua.Globals.Get(FpsNumberName).Number <= 0)
            {
                throw new Exception($"'{FpsNumberName}' number must be greater than 0");
            }

            FrameInterval = 1000 / Lua.Globals.Get(FpsNumberName).Number;
            DrawHandle    = Lua.Globals.Get(DrawFunctionName);
        }
Example #5
0
        public Script(LuaScript script, string code)
        {
            Guard.NotNull(script, nameof(script));
            Guard.NotNullOrWhiteSpace(code, nameof(code));

            this._script = script;
            this._code   = code;
        }
Example #6
0
 public Script(string path, ScriptProcessor processor)
 {
     FullPath  = path;
     Name      = Path.GetFileName(path).ToLower();
     Compiled  = new MoonSharp.Interpreter.Script(CoreModules.Preset_SoftSandbox);
     RawSource = string.Empty;
     Processor = processor;
 }
    /// <summary>
    /// hook called from LuaUIButtons
    /// </summary>
    void OnLuaUIButtonClick(GameObject button)
    {
        foreach (LuaHandler luaHandler in FindObjectsOfType <LuaHandler>())
        {
            MoonSharp.Interpreter.Script luaScript = luaHandler.luaScript;

            if (luaScript != null && luaScript.Globals["OnUIButtonClick"] != null)
            {
                luaScript.Call(luaScript.Globals["OnUIButtonClick"], Task.GetOrMakeLuaUIObject(button));
            }
        }
    }
Example #8
0
        public Script(string file, Project project)
        {
            this.file = file;

            luaScript = new LUA.Script();

            // Types
            LUA.UserData.RegisterType(typeof(Project));
            LUA.UserData.RegisterType(typeof(SourceFile));
            LUA.UserData.RegisterType(typeof(List <string>));

            // Variables
            luaScript.Globals["project"] = project;

            luaScript.Globals["Windows"] = Platform.isWin32;
            luaScript.Globals["Unix"]    = Platform.isUnix;
            luaScript.Globals["OSX"]     = Platform.isOSX;
            luaScript.Globals["Linux"]   = Platform.isLinux;

            // Functions
            luaScript.Globals["Print"]   = (Action <object>)(Logger.Normal);
            luaScript.Globals["Warning"] = (Action <object>)(Logger.Warning);
            luaScript.Globals["AddLib"]  = (Action <string>)((slib) =>
            {
                project.libraries.Add(slib);
            });

            luaScript.Globals["AddFlag"] = (Action <string>)((sopt) =>
            {
                project.cxxFlags += $"{sopt} ";
            });

            luaScript.Globals["AddLibIW"] = (Action <string>)((slib) =>
            {
                if (Platform.isWin32)
                {
                    project.libraries.Add(slib);
                }
            });

            luaScript.Globals["AddLibMP"] = (Action <string>)((slib) =>
            {
                slib = Platform.isWin32 ? $"{slib}32" : slib;
                project.libraries.Add(slib);
            });

            luaScript.DoFile(file);

            script = this;
        }
Example #9
0
        public Script CreateFor(string script)
        {
            Guard.NotNullOrWhiteSpace(script, nameof(script));

            var luaScript = new MoonSharp.Interpreter.Script(CoreModules.Preset_HardSandbox);
            var result    = new Script(luaScript, script);

            foreach (var pair in this._globalData)
            {
                result.AddData(pair.Key, pair.Value);
            }

            foreach (var pair in this._globalMethods)
            {
                result.AddMethod(pair.Key, pair.Value);
            }

            return(result);
        }
Example #10
0
 public SosigScript()
 {
     //Set Console log
     Console = BepInEx.Logging.Logger.CreateLogSource("SosigScript");
     Logger.LogInfo("Initialising SosigScript");
     //Start up MoonSharp so scripts load faster
     Logger.LogDebug("Warming up scripts");
     Script.WarmUp();
     //Give it standard platform settings
     Logger.LogDebug("Setting Platform accessors");
     Script.GlobalOptions.Platform = new StandardPlatformAccessor();
     //Make a new manual log source specifically for checking if MoonSharp is initialised
     Logger.LogDebug("Setting DebugPrint logsource");
     Script.DefaultOptions.DebugPrint = message => { BepInEx.Logging.Logger.CreateLogSource("SosigScript (INITIALISATION)").LogInfo(message); };
     //Run a print command!
     Script.RunString("print('SosigScript initialised! Hello from Lua!')");
     //We set the "Soft Sandbox" so user has more options in their scripts
     ScriptLoader  = new Script(CoreModules.Preset_SoftSandbox);
     Libraries     = new LibraryLoader();
     ActiveScripts = new List <Executioner>();
 }
 internal DynamicExpression(Script S, string strExpr, DynamicExprExpression expr)
 {
     ExpressionCode = strExpr;
     OwnerScript    = S;
     m_Exp          = expr;
 }
Example #12
0
        public virtual bool SubstituteStrings(StringBuilder input)
        {
            // This method could be called from the Start of another component, so
            // we need to ensure that the LuaEnvironment has been initialized.
            if (luaEnvironment == null)
            {
                luaEnvironment = GetComponent <LuaEnvironment>();
                if (luaEnvironment != null)
                {
                    luaEnvironment.InitEnvironment();
                }
            }

            if (luaEnvironment == null)
            {
                UnityEngine.Debug.LogError("No Lua Environment found");
                return(false);
            }

            if (luaEnvironment.Interpreter == null)
            {
                UnityEngine.Debug.LogError("No Lua interpreter found");
                return(false);
            }

            MoonSharp.Interpreter.Script interpreter = luaEnvironment.Interpreter;

            // Instantiate the regular expression object.
            Regex r = new Regex("\\{\\$.*?\\}");

            bool modified = false;

            // Match the regular expression pattern against a text string.
            var results = r.Matches(input.ToString());

            foreach (Match match in results)
            {
                string key = match.Value.Substring(2, match.Value.Length - 3);

                // Match against string table and active language (if specified)
                if (stringTable != null)
                {
                    DynValue stringTableVar = stringTable.Get(key);
                    if (stringTableVar.Type == DataType.Table)
                    {
                        DynValue languageEntry = stringTableVar.Table.Get(activeLanguage);
                        if (languageEntry.Type == DataType.String)
                        {
                            input.Replace(match.Value, languageEntry.String);
                            modified = true;
                        }
                        continue;
                    }
                }

                // Match against global variables
                DynValue globalVar = interpreter.Globals.Get(key);
                if (globalVar.Type != DataType.Nil)
                {
                    input.Replace(match.Value, globalVar.ToPrintString());
                    modified = true;
                    continue;
                }
            }

            return(modified);
        }
Example #13
0
        /// <summary>
        /// Register some commonly used Unity classes and objects for Lua interop.
        /// To register more class objects externally to this class, register them in the Awake method of any
        /// monobehavior in your scene.
        /// </summary>
        protected virtual void InitFungusModule()
        {
            if (fungusModule == FungusModuleOptions.NoFungusModule)
            {
                return;
            }

            MoonSharp.Interpreter.Script interpreter = luaEnvironment.Interpreter;

            // Require the Fungus module and assign it to the global 'fungus'
            Table fungusTable = null;

            MoonSharp.Interpreter.DynValue value = interpreter.RequireModule("fungus");
            if (value != null &&
                value.Type == DataType.Function)
            {
                fungusTable = value.Function.Call().Table;
            }
            if (fungusTable == null)
            {
                UnityEngine.Debug.LogError("Failed to create Fungus table");
                return;
            }
            interpreter.Globals["fungus"] = fungusTable;

            // Static classes
            fungusTable["time"]        = UserData.CreateStatic(typeof(Time));
            fungusTable["playerprefs"] = UserData.CreateStatic(typeof(PlayerPrefs));
            fungusTable["prefs"]       = UserData.CreateStatic(typeof(FungusPrefs));
            fungusTable["factory"]     = UserData.CreateStatic(typeof(PODTypeFactory));

            // Lua Environment and Lua Utils components
            fungusTable["luaenvironment"] = luaEnvironment;
            fungusTable["luautils"]       = this;

            // Provide access to the Unity Test Tools (if available).
            Type testType = Type.GetType("IntegrationTest");

            if (testType != null)
            {
                UserData.RegisterType(testType);
                fungusTable["test"] = UserData.CreateStatic(testType);
            }

            // Populate the string table by parsing the string table JSON files
            stringTable = new Table(interpreter);
            fungusTable["stringtable"] = stringTable;
            foreach (TextAsset stringFile in stringTables)
            {
                if (stringFile.text == "")
                {
                    continue;
                }

                JSONObject stringsJSON = new JSONObject(stringFile.text);
                if (stringsJSON == null ||
                    stringsJSON.type != JSONObject.Type.OBJECT)
                {
                    UnityEngine.Debug.LogError("String table JSON format is not correct " + stringFile.name);
                    continue;
                }

                foreach (string stringKey in stringsJSON.keys)
                {
                    if (stringKey == "")
                    {
                        UnityEngine.Debug.LogError("String table JSON format is not correct " + stringFile.name);
                        continue;
                    }

                    Table entriesTable = new Table(interpreter);
                    stringTable[stringKey] = entriesTable;

                    JSONObject entries = stringsJSON.GetField(stringKey);
                    if (entries.type != JSONObject.Type.OBJECT)
                    {
                        UnityEngine.Debug.LogError("String table JSON format is not correct " + stringFile.name);
                        continue;
                    }

                    foreach (string language in entries.keys)
                    {
                        string translation = entries.GetField(language).str;
                        entriesTable[language] = translation;
                    }
                }
            }

            stringSubstituter = new StringSubstituter();

            if (fungusModule == FungusModuleOptions.UseGlobalVariables)
            {
                // Copy all items from the Fungus table to global variables
                foreach (TablePair p in fungusTable.Pairs)
                {
                    if (interpreter.Globals.Keys.Contains(p.Key))
                    {
                        UnityEngine.Debug.LogError("Lua globals already contains a variable " + p.Key);
                    }
                    else
                    {
                        interpreter.Globals[p.Key] = p.Value;
                    }
                }

                interpreter.Globals["fungus"] = DynValue.Nil;

                // Note: We can't remove the fungus table itself because of dependencies between functions
            }
        }
Example #14
0
		internal DynamicExpression(Script S, string strExpr, DynValue constant)
		{
			ExpressionCode = strExpr;
			OwnerScript = S;
			m_Constant = constant;
		}
Example #15
0
		internal DynamicExpression(Script S, string strExpr, DynamicExprExpression expr)
		{
			ExpressionCode = strExpr;
			OwnerScript = S;
			m_Exp = expr;
		}
Example #16
0
        /// <summary>
        /// 초기화
        /// </summary>
        public void Initialize()
        {
            try
            {
                m_engine		= new Script();						// 엔진 인스턴스 초기화
                m_engine.Options.DebugPrint	= (s) =>				// lua의 print 아웃풋 설정
                    {
                        Debug.Log("[LUA Print] " + s);
                    };

                m_engine.DoFile(c_entryScript);						// 시작 스크립트 실행

                // Lua 테이블 가져오기
                m_tablePlayer			= LoadSingleScriptTable(c_field_playerScript);
                m_tableEmperor			= LoadSingleScriptTable(c_field_emperorScript);
                m_tableIndivdualList	= LoadScriptTableArray(c_field_individualScripts);
                m_tableFactionList		= LoadScriptTableArray(c_field_factionScripts);

                m_tableActivityList		= LoadScriptTableArray(c_field_activityScripts);
                m_tableItemList			= LoadScriptTableArray(c_field_itemScripts);
                m_tableEventList		= LoadScriptTableArray(c_field_eventScripts);

                m_gameTable				= DynValue.NewTable(m_engine).Table;	// 게임 오브젝트 테이블
                m_engine.Globals["Game"]	= m_gameTable;
            }

            catch(ScriptRuntimeException ex)
            {
                HandleScriptError(ex);
            }
        }
Example #17
0
        //unsupported (and never used in any SAGE game and it's mods): debug and tag methods, %upvalues
        //DEPRECATED and actually removed from original SAGE: rawgetglobal, rawsetglobal, foreachvar, nextvar

        public static void Apply(MoonSharp.Interpreter.Script script)
        {
            script.DoString(_compabilityCode);
        }
        /// <summary>
        /// Add all declared bindings to the globals table.
        /// </summary>
        public override void AddBindings(LuaEnvironment luaEnv)
        {
            if (!allEnvironments &&
                (luaEnvironment != null && !luaEnvironment.Equals(luaEnv)))
            {
                // Don't add bindings to this environment
                return;
            }

            MoonSharp.Interpreter.Script interpreter = luaEnv.Interpreter;
            Table globals = interpreter.Globals;

            Table bindingsTable = null;

            if (tableName == "")
            {
                // Add directly to globals table
                bindingsTable = globals;
            }
            else
            {
                DynValue res = globals.Get(tableName);
                if (res.Type == DataType.Table)
                {
                    // Add to an existing table
                    bindingsTable = res.Table;
                }
                else
                {
                    // Create a new table
                    bindingsTable      = new Table(globals.OwnerScript);
                    globals[tableName] = bindingsTable;
                }
            }

            if (bindingsTable == null)
            {
                Debug.LogError("Bindings table must not be null");
            }

            // Register types of bound objects with MoonSharp
            if (registerTypes)
            {
                foreach (string typeName in boundTypes)
                {
                    LuaEnvironment.RegisterType(typeName);
                }
            }

            for (int i = 0; i < boundObjects.Count; ++i)
            {
                // Ignore empty keys
                string key = boundObjects[i].key;
                if (key == null ||
                    key == "")
                {
                    continue;
                }

                // Check for keys used multiple times
                if (bindingsTable.Get(key).Type != DataType.Nil)
                {
                    Debug.LogWarning("An item already exists with the same key as binding '" + key + "'. This binding will be ignored.");
                    continue;
                }

                // Ignore bindings with no object set
                GameObject go = boundObjects[i].obj as GameObject;
                if (go != null)
                {
                    // Register as gameobject / components
                    Component component = boundObjects[i].component;
                    if (component == null)
                    {
                        // Bind the key to the gameobject
                        bindingsTable[key] = go;
                    }
                    else
                    {
                        // Bind the key to the component
                        bindingsTable[key] = component;
                    }
                }
                else
                {
                    // Register as other UnityEngine.Object type
                    bindingsTable[key] = boundObjects[i].obj;
                }
            }
        }
 internal DynamicExpression(Script S, string strExpr, DynValue constant)
 {
     ExpressionCode = strExpr;
     OwnerScript    = S;
     m_Constant     = constant;
 }
Example #20
0
 public GameEvent(Script eventScript)
 {
     this.eventScript = eventScript;
 }
Example #21
0
 public bool Reload()
 {
     Compiled = new MoonSharp.Interpreter.Script(CoreModules.Preset_SoftSandbox);
     return(Run());
 }