IEnumerator LuaRoutine() { bool pause = false; Debug.Log("start!"); var script = new Script(); script.Options.DebugPrint = s => Debug.Log(s); script.Globals["csharpfunc"] = (System.Action)delegate() { pause = true; }; var function = script.DoFile("testscript"); var coroutine = script.CreateCoroutine(function); do { coroutine.Coroutine.Resume(); Debug.Log("C sharp side"); yield return new WaitForSeconds(3); } while (coroutine.Coroutine.State != CoroutineState.Dead); yield break; }
public static void Init() { // Create directories if (!Directory.Exists(RootScriptDir)) Directory.CreateDirectory(RootScriptDir); if (!Directory.Exists(RootLibScriptDir)) Directory.CreateDirectory(RootLibScriptDir); // Initialize list Scripts = new List<Script>(); Console.WriteLine(Directory.GetFiles(RootScriptDir).Count()); Script.DefaultOptions.ScriptLoader = new ReplInterpreterScriptLoader(); foreach (var scriptFile in Directory.GetFiles(RootScriptDir)) { var script = new Script(); ((ScriptLoaderBase)script.Options.ScriptLoader).ModulePaths = new[] { Path.Combine(RootLibScriptDir, "?"), Path.Combine(RootLibScriptDir, "?.lua") }; ApiHandler.AddApi(script); //Get each lib file, and load it to the script /* foreach (var libFile in Directory.GetFiles(RootLibScriptDir)) { script.LoadFile(libFile); } //*/ // Run the script :D script.DoFile(scriptFile); // Add script to the list Scripts.Add(script); } }
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; }
public static void LoadEventScripts() { try { var script = new Script(); script.Globals["isTrue"] = true; script.DoFile("LuaTest"); if (script.Call(script.Globals["predicate"]).Boolean) { script.Call(script.Globals["onResolve"]); } } catch (ScriptRuntimeException ex) { Debug.LogError("Doh! An error occured! " + ex.DecoratedMessage); } }
/// <summary> /// Runs the specified file with all possible defaults for quick experimenting. /// </summary> /// <param name="filename">The filename.</param> /// A DynValue containing the result of the processing of the executed script. public static DynValue RunFile(string filename) { Script S = new Script(); return S.DoFile(filename); }
private static void ParseCommand(Script S, string p) { if (p == "help") { Console.WriteLine("Type Lua code to execute Lua code, multilines are accepted, "); Console.WriteLine("or type one of the following commands to execute them."); Console.WriteLine(""); Console.WriteLine("Commands:"); Console.WriteLine(""); Console.WriteLine(" !exit - Exits the interpreter"); Console.WriteLine(" !debug - Starts the debugger"); Console.WriteLine(" !run <filename> - Executes the specified Lua script"); Console.WriteLine(" !compile <filename> - Compiles the file in a binary format"); Console.WriteLine(""); } else if (p == "exit") { Environment.Exit(0); } else if (p == "debug" && m_Debugger == null) { m_Debugger = new RemoteDebuggerService(); m_Debugger.Attach(S, "MoonSharp REPL interpreter", false); Process.Start(m_Debugger.HttpUrlStringLocalHost); } else if (p.StartsWith("run")) { p = p.Substring(3).Trim(); S.DoFile(p); } else if (p == "!") { ParseCommand(S, "debug"); ParseCommand(S, @"run c:\temp\test.lua"); } else if (p.StartsWith("compile")) { p = p.Substring("compile".Length).Trim(); string targetFileName = p + "-compiled"; DynValue chunk = S.LoadFile(p); using (Stream stream = new FileStream(targetFileName, FileMode.Create, FileAccess.Write)) S.Dump(chunk, stream); } }
static void Main(string[] args) { Script.DefaultOptions.ScriptLoader = new ReplInterpreterScriptLoader(); Console.WriteLine("MoonSharp REPL {0} [{1}]", Script.VERSION, Script.GlobalOptions.Platform.GetPlatformName()); Console.WriteLine("Copyright (C) 2014-2015 Marco Mastropaolo"); Console.WriteLine("http://www.moonsharp.org"); Console.WriteLine(); if (args.Length == 1) { Script script = new Script(); script.DoFile(args[0]); Console.WriteLine("Done."); if (System.Diagnostics.Debugger.IsAttached) Console.ReadKey(); } else { Console.WriteLine("Type Lua code to execute it or type !help to see help on commands.\n"); Console.WriteLine("Welcome.\n"); Script script = new Script(CoreModules.Preset_Complete); ReplInterpreter interpreter = new ReplInterpreter(script) { HandleDynamicExprs = true, HandleClassicExprsSyntax = true }; while (true) { Console.Write(interpreter.ClassicPrompt + " "); string s = Console.ReadLine(); if (!interpreter.HasPendingCommand && s.StartsWith("!")) { ParseCommand(script, s.Substring(1)); continue; } try { DynValue result = interpreter.Evaluate(s); if (result != null && result.Type != DataType.Void) Console.WriteLine("{0}", result); } catch (InterpreterException ex) { Console.WriteLine("{0}", ex.DecoratedMessage ?? ex.Message); } catch (Exception ex) { Console.WriteLine("{0}", ex.Message); } } } }
/// <summary> /// Runs the specified file with all possible defaults for quick experimenting. /// </summary> /// <param name="filename">The filename.</param> /// A DynValue containing the result of the processing of the executed script. public static DynValue RunFile(string filename) { Script S = new Script(); return(S.DoFile(filename)); }
/// <summary> /// Asynchronously loads and executes a file containing a Lua/MoonSharp script. /// /// This method is supported only on .NET 4.x and .NET 4.x PCL targets. /// </summary> /// <param name="script">The script.</param> /// <param name="filename">The filename.</param> /// <param name="globalContext">The global context.</param> /// <returns> /// A DynValue containing the result of the processing of the loaded chunk. /// </returns> public static Task <DynValue> DoFile(this Script script, string filename, Table globalContext = null) { return(ExecAsync(() => script.DoFile(filename, globalContext))); }
/// <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); } }
/// <summary> /// Load the mods in the mods folder /// </summary> public static void LoadMods() { Console.WriteLine("\n[dungeontest] loading mods\n"); // Set script loader //Script.DefaultOptions.ScriptLoader = new EmbeddedResourcesScriptLoader(); // Register classes UserData.RegisterType<API>(); UserData.RegisterType<Input>(); UserData.RegisterType<Block>(); UserData.RegisterType<Entity>(); UserData.RegisterType<Keys>(); UserData.RegisterType<Vector2>(); // Load static classes DynValue api = UserData.Create(new API()); DynValue input = UserData.Create(new Input()); DynValue keys = UserData.Create(new Keys()); // Script Loader Base //((ScriptLoaderBase)script.Options.ScriptLoader).ModulePaths = new string[] { "mods/?", "mods/?.lua" }; //((ScriptLoaderBase)script.Options.ScriptLoader).IgnoreLuaPathGlobal = true; foreach (string file in Directory.EnumerateFiles(MODS_FOLDER, "*.lua")) { Console.Write("\n[dungeontest] initializing mod '{0}'\n", file); try { Script script = new Script(); script.Globals.Set("API", api); script.Globals.Set("Input", input); script.Globals.Set("Keys", keys); // Load the file script.DoFile(file); mods.Add(script); // Log completion Console.WriteLine("\n[dungeontest] mod '{0}' loaded!\n", file); } catch (ScriptRuntimeException ex) { // Alerting the issue loading a mod Console.WriteLine("\n[dungeontest] error occured in loading '{0}' mod: {1}\n", file, ex.Message); Console.WriteLine("\n[dungeontest] could not load '{0}' mod!\n", file); } // Print how many mods were loaded Console.WriteLine("\n[dungeontest] {0} mods have been loaded\n", mods.Count); } }
/// <summary> /// Asynchronously loads and executes a file containing a Lua/MoonSharp script. /// /// This method is supported only on .NET 4.x and .NET 4.x PCL targets. /// </summary> /// <param name="script">The script.</param> /// <param name="filename">The filename.</param> /// <param name="globalContext">The global context.</param> /// <param name="codeFriendlyName">Name of the code - used to report errors, etc. Also used by debuggers to locate the original source file.</param> /// <returns> /// A DynValue containing the result of the processing of the loaded chunk. /// </returns> public static Task <DynValue> DoFileAsync(this Script script, string filename, Table globalContext = null, string codeFriendlyName = null) { return(ExecAsync(() => script.DoFile(filename, globalContext, codeFriendlyName))); }
private static bool CheckArgs(string[] args, ShellContext shellContext) { if (args.Length == 0) return false; if (args.Length == 1 && args[0].Length > 0 && args[0][0] != '-') { Script script = new Script(); script.DoFile(args[0]); } if (args[0] == "-H" || args[0] == "--help" || args[0] == "/?" || args[0] == "-?") { ShowCmdLineHelpBig(); } else if (args[0] == "-X") { if (args.Length == 2) { ExecuteCommand(shellContext, args[1]); } else { Console.WriteLine("Wrong syntax."); ShowCmdLineHelp(); } } else if (args[0] == "-W") { bool internals = false; string dumpfile = null; string destfile = null; string classname = null; string namespacename = null; bool useVb = false; bool fail = true; for (int i = 1; i < args.Length; i++) { if (args[i] == "--internals") internals = true; else if (args[i] == "--vb") useVb = true; else if (args[i].StartsWith("--class:")) classname = args[i].Substring("--class:".Length); else if (args[i].StartsWith("--namespace:")) namespacename = args[i].Substring("--namespace:".Length); else if (dumpfile == null) dumpfile = args[i]; else if (destfile == null) { destfile = args[i]; fail = false; } else fail = true; } if (fail) { Console.WriteLine("Wrong syntax."); ShowCmdLineHelp(); } else { HardWireCommand.Generate(useVb ? "vb" : "cs", dumpfile, destfile, internals, classname, namespacename); } } return true; }
static void EmbeddedResourceScriptLoader() { Script script = new Script(); script.Options.ScriptLoader = new EmbeddedResourcesScriptLoader(Assembly.GetExecutingAssembly()); script.DoFile("Scripts/Test.lua"); }