static void Main(string[] args) { UserData.RegisterType<Foo>(); UserData.RegisterType<Dictionary<int, int>>(); UserData.RegisterExtensionType(typeof(FooExtension)); var lua = new Script(); lua.Globals["DictionaryIntInt"] = typeof(Dictionary<int, int>); var script = @"local dict = DictionaryIntInt.__new(); local res, v = dict.TryGetValue(0)"; lua.DoString(script); lua.DoString(script); //var lua = new Script(); //lua.Globals["Foo"] = typeof(Foo); //var script = @"local _, obj = Foo.Test1('ciao', 'hello'); print(obj);"; //lua.DoString(script); Console.WriteLine("Done"); Console.ReadKey(); }
public static void xxMain() { string code = @" function a() callback(b) end function b() coroutine.yield(); end c = coroutine.create(a); return coroutine.resume(c); "; // Load the code and get the returned function Script script = new Script(); script.Globals["callback"] = DynValue.NewCallback( (ctx, args) => args[0].Function.Call() ); DynValue ret = script.DoString(code); // false, "attempt to yield from outside a coroutine" Console.WriteLine(ret); Console.ReadKey(); }
private void CallButton_Click(object sender, RoutedEventArgs e) { string scriptCode = Chunk.Text; // Register types to be used in the script. UserData.RegisterType<BusinessObject>(); UserData.RegisterType<EventArgs>(); Script script = new Script(); try { var obj = UserData.Create(bus); script.Globals.Set("obj", obj); script.DoString(scriptCode); Result.Foreground = new SolidColorBrush(Colors.Black); Result.Text = "done"; } catch (Exception ex) { Result.Foreground = new SolidColorBrush(Colors.Red); Result.Text = ex.Message; } }
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); }
static void CoroutinesFromCSharp() { string code = @" return function() local x = 0 while true do x = x + 1 coroutine.yield(x) end end "; // Load the code and get the returned function Script script = new Script(); DynValue function = script.DoString(code); // Create the coroutine in C# DynValue coroutine = script.CreateCoroutine(function); // Resume the coroutine forever and ever.. while (true) { DynValue x = coroutine.Coroutine.Resume(); Console.WriteLine("{0}", x); } }
static void CoroutinesAsCSharpIterator() { string code = @" return function() local x = 0 while true do x = x + 1 coroutine.yield(x) if (x > 5) then return 7 end end end "; // Load the code and get the returned function Script script = new Script(); DynValue function = script.DoString(code); // Create the coroutine in C# DynValue coroutine = script.CreateCoroutine(function); // Loop the coroutine string ret = ""; foreach (DynValue x in coroutine.Coroutine.AsTypedEnumerable()) { ret = ret + x.ToString(); } Console.WriteLine(ret); }
// This prints : // 3 // hello world // 3 // hello world // 3 // hello world // 3 // hello world // Done public static void xxMain() { string code = @" x = 3 function onThis() print(x) x = 'hello' end function onThat() print(x .. ' world') x = 3 end "; // Load the code Script script = new Script(); script.DoString(code); var onThis = script.Globals.Get("onThis").Function.GetDelegate(); var onThat = script.Globals.Get("onThat").Function.GetDelegate(); for (int i = 0; i < 4; i++) { onThis(); onThat(); } Console.WriteLine("Done"); Console.ReadKey(); }
static void DebuggerDemo() { Script script = new Script(); ActivateRemoteDebugger(script); script.DoString(@" function accum(n, f) if (n == 0) then return 1; else return n * f(n); end end local sum = 0; for i = 1, 5 do -- let's use a lambda to spice things up sum = sum + accum(i, | x | x - 1); end "); Console.WriteLine("The script has ended.."); }
public override string Parse(string Name, List<string> args) { Script script = new Script(); UserData.RegisterType<List<string>>(); script.Globals.SetAsObject("args", args); script.Globals.SetAsObject("argsl", args.Count - 1); return script.DoString(Lua).String; }
private void Form1_Load(object sender, EventArgs e) { CheckString(lblVersion, EXPECTEDVERSION, Script.VERSION); CheckString(lblPlatform, EXPECTEDPLATF, Script.GlobalOptions.Platform.GetPlatformName()); Script S = new Script(); DynValue fn = S.DoString(BASICSCRIPT); string res = fn.Function.Call(2, 3, 4).String; CheckString(lblTestResult, "20", res); }
static string ErrorGen() { string scriptCode = @" local _, msg = pcall(DoError); return msg; "; Script script = new Script(); script.Globals["DoError"] = (Action)DoError; DynValue res = script.DoString(scriptCode); return res.String; }
private void button1_Click(object sender, EventArgs e) { Script S = new Script(); DynValue fn = S.DoString(BASICSCRIPT); ActivateRemoteDebugger(S); string res = fn.Function.Call(2, 3, 4).String; CheckString(lblTestResult, "20", res); }
static void CustomScriptLoader() { Script script = new Script(); script.Options.ScriptLoader = new MyCustomScriptLoader() { ModulePaths = new string[] { "?_module.lua" } }; script.DoString(@" require 'somemodule' f = loadfile 'someothermodule.lua' f() "); }
static void Main(string[] args) { string scriptCode = @"return obj.calcHypotenuse(3, 4);"; // Automatically register all MoonSharpUserData types UserData.RegisterAssembly(); Script script = new Script(); // Pass an instance of MyClass to the script in a global script.Globals["obj"] = new MyClass(); DynValue res = script.DoString(scriptCode); return; }
static void ErrorHandling() { try { string scriptCode = @" return obj.calcHypotenuse(3, 4); "; Script script = new Script(); DynValue res = script.DoString(scriptCode); } catch (ScriptRuntimeException ex) { Console.WriteLine("Doh! An error occured! {0}", ex.DecoratedMessage); } }
private void UserControl_Loaded(object sender, RoutedEventArgs e) { 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(); Console_WriteLine("Type Lua code in the text box below to execute it."); Console_WriteLine("The 'io', 'file' and parts of the 'os' modules are not available due to Silverlight restrictions."); Console_WriteLine("Type list() or list(<table>) to see which globals are available."); Console_WriteLine(); Console_WriteLine("Welcome."); Console_WriteLine(); script = new Script(CoreModules.Preset_Complete); script.DoString(@" local function pad(str, len) str = str .. ' ' .. string.rep('.', len); str = string.sub(str, 1, len); return str; end function list(lib) if (lib == nil) then lib = _G; end if (type(lib) ~= 'table') then print('A table was expected to list command.'); return end for k, v in pairs(lib) do print(pad(type(v), 12) .. ' ' .. k) end end"); script.Options.DebugPrint = s => Console_WriteLine(s); interpreter = new ReplHistoryInterpreter(script, 100) { HandleDynamicExprs = true, HandleClassicExprsSyntax = true }; DoPrompt(); }
public static double MoonSharpFactorial2() { string scriptCode = @" -- defines a factorial function function fact (n) if (n == 0) then return 1 else return n*fact(n - 1) end end"; Script script = new Script(); script.DoString(scriptCode); DynValue res = script.Call(script.Globals["fact"], 4); return res.Number; }
public void ExecuteUserCode(string externalCode) { try { Logger.Info($"Executing user code {externalCode}"); MainScript.DoString(externalCode); } catch (SyntaxErrorException exeption) { throw (exeption); } catch (ScriptRuntimeException exeption) { throw (exeption); } catch (Exception exeption) { throw (exeption); } }
private void Start() { //UserData.DefaultAccessMode = InteropAccessMode.Preoptimized; UserData.RegisterAssembly(); //var nLuaState = new Lua(); var moonSharpState = new Script(); const string script = @" a = """" onUpdate = function(championPropertiesComponent) a = championPropertiesComponent:getName() end "; //nLuaState.DoString(script); moonSharpState.DoString(script); var championProperties = new ChampionPropertiesComponent(); championProperties.SetFirstName("John"); championProperties.SetLastName("Smith"); //var nLuaFunction = (LuaFunction)nLuaState["onUpdate"]; var moonSharpFunction = (Closure)moonSharpState.Globals["onUpdate"]; int startTime, endTime; //// Test NLua //startTime = Environment.TickCount; //for (int i = 0; i < 100000; i++) nLuaFunction.Call(championProperties.ToInterface()); //endTime = Environment.TickCount; //Console.WriteLine("NLua : {0}", endTime - startTime); // Test MoonSharp startTime = Environment.TickCount; //DynValue v = DynValue.FromObject(moonSharpState, championProperties.ToInterface()); for (int i = 0; i < 100000; i++) moonSharpFunction.Call(championProperties.ToInterface()); endTime = Environment.TickCount; Console.WriteLine("MoonSharp : {0}", endTime - startTime); }
public static double TableTest2() { string scriptCode = @" total = 0; tbl = getNumbers() for _, i in ipairs(tbl) do total = total + i; end return total; "; Script script = new Script(); script.Globals["getNumbers"] = (Func<Script, Table>)(GetNumberTable); DynValue res = script.DoString(scriptCode); return res.Number; }
static void Main(string[] args) { Script S = new Script(CoreModules.Basic); RemoteDebuggerService remoteDebugger; remoteDebugger = new RemoteDebuggerService(); remoteDebugger.Attach(S, "MyScript", false); Process.Start(remoteDebugger.HttpUrlStringLocalHost); S.DoString(@" local hi = 'hello' local function test() print(hi) end test(); hi = 'X' test(); local hi = '!'; test(); "); Console.WriteLine("DONE"); Console.ReadKey(); }
private void Button_Click(object sender, RoutedEventArgs e) { string scriptCode = Chunk.Text; // Register the type(s) to be used in the script. // Automatically register all classes with the MoonSharpUserData attribute. // UserData.RegisterAssembly(); // Hey, that did not work (not here and not in WPF) // Automatically register all types. Pandora's box. // UserData.RegistrationPolicy = InteropRegistrationPolicy.Automatic; UserData.RegisterType<BusinessObject>(); Script script = new Script(); try { var obj = UserData.Create(new BusinessObject()); // Actually, this also works: // var obj = new BusinessObject(); script.Globals["obj"] = obj; // Alternatively: //script.Globals.Set("obj", obj); script.DoString(scriptCode); Result.Foreground = new SolidColorBrush(Colors.Black); Result.Text = "done"; } catch (Exception ex) { Result.Foreground = new SolidColorBrush(Colors.Red); Result.Text = ex.Message; } }
private void Button_Click(object sender, RoutedEventArgs e) { string scriptCode = Chunk.Text; Script script = new Script(); try { // Expose the C# methods. script.Globals["say"] = (Action<String>)(Say); script.Globals["reverse"] = (Func<String, String>)(Reverse); script.DoString(scriptCode); Result.Foreground = new SolidColorBrush(Colors.Black); Result.Text = "done"; } catch (Exception ex) { Result.Foreground = new SolidColorBrush(Colors.Red); Result.Text = ex.Message; } }
private void Button_Click(object sender, RoutedEventArgs e) { string scriptCode = "function f(a,b) " + Chunk.Text + " end"; var script = new Script(); try { script.DoString(scriptCode); DynValue luaFunction = script.Globals.Get("f"); // Type conversion for the parameters is optional DynValue res = script.Call( luaFunction, DynValue.NewString(ParameterA.Text).CastToNumber(), Double.Parse(ParameterB.Text)); // Check the return type. if (res.Type != DataType.Number) { throw new InvalidCastException("Invalid return type: " + res.Type.ToString()); } Result.Foreground = new SolidColorBrush(Colors.Black); // Type conversion swallows exceptions. Result.Text = res.Number.ToString(); // Result.Text = res.CastToNumber().ToString(); } catch (Exception ex) { Result.Foreground = new SolidColorBrush(Colors.Red); Result.Text = ex.Message; } }
private static void TableTestReverseSafer() { string scriptCode = @" return dosum { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 } "; Script script = new Script(); // Safer to assume that the Table is a list of objects, than to implicitely cast to ints. script.Globals["dosum"] = (Func<List<object>, double>)(l => l.OfType<double>().Sum()); DynValue res = script.DoString(scriptCode); Console.WriteLine(res.Number); }
/// <summary> /// Runs the specified code with all possible defaults for quick experimenting. /// </summary> /// <param name="code">The Lua/MoonSharp code.</param> /// A DynValue containing the result of the processing of the executed script. public static DynValue RunString(string code) { Script S = new Script(); return S.DoString(code); }
public override void Load(string code = "") { try { UserData.RegistrationPolicy = InteropRegistrationPolicy.Automatic; script = new Script(); script.Globals["Plugin"] = this; script.Globals["Util"] = Util.GetInstance(); script.Globals["Server"] = Server.GetInstance(); script.Globals["DataStore"] = DataStore.GetInstance(); script.Globals["Commands"] = chatCommands; script.Globals["GlobalData"] = GlobalData; script.Globals["ServerConsoleCommands"] = consoleCommands; script.Globals["Web"] = Web.GetInstance(); script.Globals["World"] = World.GetInstance(); script.DoString(code); Author = script.Globals.Get("Author").String; About = script.Globals.Get("About").String; Version = script.Globals.Get("Version").String; State = PluginState.Loaded; foreach (DynValue v in script.Globals.Keys) { Globals.Add(v.ToString().Replace("\"", "")); } Tables = script.Globals; } catch (Exception ex) { Logger.LogException(ex); State = PluginState.FailedToLoad; } PluginLoader.GetInstance().OnPluginLoaded(this); }
private void LoadFile(string fileName) { script = new Script(); TextAsset ta = Resources.Load(fileName) as TextAsset; script.DoString(ta.text); }
/// <summary> /// Runs the specified code with all possible defaults for quick experimenting. /// </summary> /// <param name="code">The Lua/MoonSharp code.</param> /// A DynValue containing the result of the processing of the executed script. public static DynValue RunString(string code) { Script S = new Script(); return(S.DoString(code)); }
/// <summary> /// Asynchronously loads and executes a string 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="code">The code.</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> DoStringAsync(this Script script, string code, Table globalContext = null, string codeFriendlyName = null) { return(ExecAsync(() => script.DoString(code, globalContext, codeFriendlyName))); }
private static void TableTestReverse() { string scriptCode = @" return dosum { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 } -- call dosum with the given table "; Script script = new Script(); script.Globals["dosum"] = (Func<List<int>, int>)(l => l.Sum()); // the table becomes a List<T>! DynValue res = script.DoString(scriptCode); Console.WriteLine(res.Number); }
//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); }
private void CreateLuaInstance() { _lua = new Script(CoreModules.Preset_SoftSandbox | CoreModules.LoadMethods); _lua.Options.ScriptLoader = new CustomScriptLoader(_path) { ModulePaths = new [] { "?.lua" } }; _lua.Options.CheckThreadAccess = false; _lua.Globals["log"] = new Action<string>(Log); _lua.Globals["fatal"] = new Action<string>(Fatal); _lua.Globals["stringContains"] = new Func<string, string, bool>(StringContains); // General conditions _lua.Globals["getPlayerX"] = new Func<int>(GetPlayerX); _lua.Globals["getPlayerY"] = new Func<int>(GetPlayerY); _lua.Globals["getMapName"] = new Func<string>(GetMapName); _lua.Globals["getTeamSize"] = new Func<int>(GetTeamSize); _lua.Globals["getPokemonId"] = new Func<int, int>(GetPokemonId); _lua.Globals["getPokemonName"] = new Func<int, string>(GetPokemonName); _lua.Globals["getPokemonHealth"] = new Func<int, int>(GetPokemonHealth); _lua.Globals["getPokemonHealthPercent"] = new Func<int, int>(GetPokemonHealthPercent); _lua.Globals["getPokemonMaxHealth"] = new Func<int, int>(GetPokemonMaxHealth); _lua.Globals["getPokemonLevel"] = new Func<int, int>(GetPokemonLevel); _lua.Globals["getPokemonTotalExperience"] = new Func<int, int>(GetPokemonTotalExperience); _lua.Globals["getPokemonRemainingExperience"] = new Func<int, int>(GetPokemonRemainingExperience); _lua.Globals["getPokemonStatus"] = new Func<int, string>(GetPokemonStatus); _lua.Globals["getPokemonHeldItem"] = new Func<int, string>(GetPokemonHeldItem); _lua.Globals["getPokemonUniqueId"] = new Func<int, int>(GetPokemonUniqueId); _lua.Globals["getRemainingPowerPoints"] = new Func<int, string, int>(GetRemainingPowerPoints); _lua.Globals["getPokemonMaxPowerPoints"] = new Func<int, int, int>(GetPokemonMaxPowerPoints); _lua.Globals["isPokemonShiny"] = new Func<int, bool>(IsPokemonShiny); _lua.Globals["getPokemonMoveName"] = new Func<int, int, string>(GetPokemonMoveName); _lua.Globals["getPokemonMoveAccuracy"] = new Func<int, int, int>(GetPokemonMoveAccuracy); _lua.Globals["getPokemonMovePower"] = new Func<int, int, int>(GetPokemonMovePower); _lua.Globals["getPokemonMoveType"] = new Func<int, int, string>(GetPokemonMoveType); _lua.Globals["getPokemonMoveDamageType"] = new Func<int, int, string>(GetPokemonMoveDamageType); _lua.Globals["getPokemonMoveStatus"] = new Func<int, int, bool>(GetPokemonMoveStatus); _lua.Globals["getPokemonNature"] = new Func<int, string>(GetPokemonNature); _lua.Globals["getPokemonAbility"] = new Func<int, string>(GetPokemonAbility); _lua.Globals["getPokemonEffortValue"] = new Func<int, string, int>(GetPokemonEffortValue); _lua.Globals["getPokemonIndividualValue"] = new Func<int, string, int>(GetPokemonIndividualValue); _lua.Globals["getPokemonHappiness"] = new Func<int, int>(GetPokemonHappiness); _lua.Globals["getPokemonRegion"] = new Func<int, string>(GetPokemonRegion); _lua.Globals["getPokemonOriginalTrainer"] = new Func<int, string>(GetPokemonOriginalTrainer); _lua.Globals["getPokemonGender"] = new Func<int, string>(GetPokemonGender); _lua.Globals["isPokemonUsable"] = new Func<int, bool>(IsPokemonUsable); _lua.Globals["getUsablePokemonCount"] = new Func<int>(GetUsablePokemonCount); _lua.Globals["hasMove"] = new Func<int, string, bool>(HasMove); _lua.Globals["hasItem"] = new Func<string, bool>(HasItem); _lua.Globals["getItemQuantity"] = new Func<string, int>(GetItemQuantity); _lua.Globals["hasPokemonInTeam"] = new Func<string, bool>(HasPokemonInTeam); _lua.Globals["isTeamSortedByLevelAscending"] = new Func<bool>(IsTeamSortedByLevelAscending); _lua.Globals["isTeamSortedByLevelDescending"] = new Func<bool>(IsTeamSortedByLevelDescending); _lua.Globals["isTeamRangeSortedByLevelAscending"] = new Func<int, int, bool>(IsTeamRangeSortedByLevelAscending); _lua.Globals["isTeamRangeSortedByLevelDescending"] = new Func<int, int, bool>(IsTeamRangeSortedByLevelDescending); _lua.Globals["isNpcVisible"] = new Func<string, bool>(IsNpcVisible); _lua.Globals["isNpcOnCell"] = new Func<int, int, bool>(IsNpcOnCell); _lua.Globals["isShopOpen"] = new Func<bool>(IsShopOpen); _lua.Globals["getMoney"] = new Func<int>(GetMoney); _lua.Globals["isMounted"] = new Func<bool>(IsMounted); _lua.Globals["isPrivateMessageEnabled"] = new Func<bool>(IsPrivateMessageEnabled); _lua.Globals["getTime"] = new GetTimeDelegate(GetTime); _lua.Globals["isMorning"] = new Func<bool>(IsMorning); _lua.Globals["isNoon"] = new Func<bool>(IsNoon); _lua.Globals["isNight"] = new Func<bool>(IsNight); _lua.Globals["isOutside"] = new Func<bool>(IsOutside); _lua.Globals["isCurrentPCBoxRefreshed"] = new Func<bool>(IsCurrentPCBoxRefreshed); _lua.Globals["getCurrentPCBoxId"] = new Func<int>(GetCurrentPCBoxId); _lua.Globals["isPCOpen"] = new Func<bool>(IsPCOpen); _lua.Globals["getCurrentPCBoxId"] = new Func<int>(GetCurrentPCBoxId); _lua.Globals["getCurrentPCBoxSize"] = new Func<int>(GetCurrentPCBoxSize); _lua.Globals["getPCBoxCount"] = new Func<int>(GetPCBoxCount); _lua.Globals["getPCPokemonCount"] = new Func<int>(GetPCPokemonCount); _lua.Globals["getPokemonIdFromPC"] = new Func<int, int, int>(GetPokemonIdFromPC); _lua.Globals["getPokemonNameFromPC"] = new Func<int, int, string>(GetPokemonNameFromPC); _lua.Globals["getPokemonHealthFromPC"] = new Func<int, int, int>(GetPokemonHealthFromPC); _lua.Globals["getPokemonHealthPercentFromPC"] = new Func<int, int, int>(GetPokemonHealthPercentFromPC); _lua.Globals["getPokemonMaxHealthFromPC"] = new Func<int, int, int>(GetPokemonMaxHealthFromPC); _lua.Globals["getPokemonLevelFromPC"] = new Func<int, int, int>(GetPokemonLevelFromPC); _lua.Globals["getPokemonTotalExperienceFromPC"] = new Func<int, int, int>(GetPokemonTotalExperienceFromPC); _lua.Globals["getPokemonRemainingExperienceFromPC"] = new Func<int, int, int>(GetPokemonRemainingExperienceFromPC); _lua.Globals["getPokemonStatusFromPC"] = new Func<int, int, string>(GetPokemonStatusFromPC); _lua.Globals["getPokemonHeldItemFromPC"] = new Func<int, int, string>(GetPokemonHeldItemFromPC); _lua.Globals["getPokemonUniqueIdFromPC"] = new Func<int, int, int>(GetPokemonUniqueIdFromPC); _lua.Globals["getPokemonRemainingPowerPointsFromPC"] = new Func<int, int, int, int>(GetPokemonRemainingPowerPointsFromPC); _lua.Globals["getPokemonMaxPowerPointsFromPC"] = new Func<int, int, int, int>(GetPokemonMaxPowerPointsFromPC); _lua.Globals["isPokemonFromPCShiny"] = new Func<int, int, bool>(IsPokemonFromPCShiny); _lua.Globals["getPokemonMoveNameFromPC"] = new Func<int, int, int, string>(GetPokemonMoveNameFromPC); _lua.Globals["getPokemonMoveAccuracyFromPC"] = new Func<int, int, int, int>(GetPokemonMoveAccuracyFromPC); _lua.Globals["getPokemonMovePowerFromPC"] = new Func<int, int, int, int>(GetPokemonMovePowerFromPC); _lua.Globals["getPokemonMoveTypeFromPC"] = new Func<int, int, int, string>(GetPokemonMoveTypeFromPC); _lua.Globals["getPokemonMoveDamageTypeFromPC"] = new Func<int, int, int, string>(GetPokemonMoveDamageTypeFromPC); _lua.Globals["getPokemonMoveStatusFromPC"] = new Func<int, int, int, bool>(GetPokemonMoveStatusFromPC); _lua.Globals["getPokemonNatureFromPC"] = new Func<int, int, string>(GetPokemonNatureFromPC); _lua.Globals["getPokemonAbilityFromPC"] = new Func<int, int, string>(GetPokemonAbilityFromPC); _lua.Globals["getPokemonEffortValueFromPC"] = new Func<int, int, string, int>(GetPokemonEffortValueFromPC); _lua.Globals["getPokemonIndividualValueFromPC"] = new Func<int, int, string, int>(GetPokemonIndividualValueFromPC); _lua.Globals["getPokemonHappinessFromPC"] = new Func<int, int, int>(GetPokemonHappinessFromPC); _lua.Globals["getPokemonRegionFromPC"] = new Func<int, int, string>(GetPokemonRegionFromPC); _lua.Globals["getPokemonOriginalTrainerFromPC"] = new Func<int, int, string>(GetPokemonOriginalTrainerFromPC); _lua.Globals["getPokemonGenderFromPC"] = new Func<int, int, string>(GetPokemonGenderFromPC); // Battle conditions _lua.Globals["isOpponentShiny"] = new Func<bool>(IsOpponentShiny); _lua.Globals["isAlreadyCaught"] = new Func<bool>(IsAlreadyCaught); _lua.Globals["isWildBattle"] = new Func<bool>(IsWildBattle); _lua.Globals["getActivePokemonNumber"] = new Func<int>(GetActivePokemonNumber); _lua.Globals["getOpponentId"] = new Func<int>(GetOpponentId); _lua.Globals["getOpponentName"] = new Func<string>(GetOpponentName); _lua.Globals["getOpponentHealth"] = new Func<int>(GetOpponentHealth); _lua.Globals["getOpponentHealthPercent"] = new Func<int>(GetOpponentHealthPercent); _lua.Globals["getOpponentLevel"] = new Func<int>(GetOpponentLevel); _lua.Globals["getOpponentStatus"] = new Func<string>(GetOpponentStatus); _lua.Globals["isOpponentEffortValue"] = new Func<string, bool>(IsOpponentEffortValue); // Path actions _lua.Globals["moveToCell"] = new Func<int, int, bool>(MoveToCell); _lua.Globals["moveToMap"] = new Func<string, bool>(MoveToMap); _lua.Globals["moveToRectangle"] = new Func<int, int, int, int, bool>(MoveToRectangle); _lua.Globals["moveToGrass"] = new Func<bool>(MoveToGrass); _lua.Globals["moveToWater"] = new Func<bool>(MoveToWater); _lua.Globals["moveNearExit"] = new Func<string, bool>(MoveNearExit); _lua.Globals["talkToNpc"] = new Func<string, bool>(TalkToNpc); _lua.Globals["talkToNpcOnCell"] = new Func<int, int, bool>(TalkToNpcOnCell); _lua.Globals["usePokecenter"] = new Func<bool>(UsePokecenter); _lua.Globals["swapPokemon"] = new Func<int, int, bool>(SwapPokemon); _lua.Globals["swapPokemonWithLeader"] = new Func<string, bool>(SwapPokemonWithLeader); _lua.Globals["sortTeamByLevelAscending"] = new Func<bool>(SortTeamByLevelAscending); _lua.Globals["sortTeamByLevelDescending"] = new Func<bool>(SortTeamByLevelDescending); _lua.Globals["sortTeamRangeByLevelAscending"] = new Func<int, int, bool>(SortTeamRangeByLevelAscending); _lua.Globals["sortTeamRangeByLevelDescending"] = new Func<int, int, bool>(SortTeamRangeByLevelDescending); _lua.Globals["buyItem"] = new Func<string, int, bool>(BuyItem); _lua.Globals["usePC"] = new Func<bool>(UsePC); _lua.Globals["openPCBox"] = new Func<int, bool>(OpenPCBox); _lua.Globals["depositPokemonToPC"] = new Func<int, bool>(DepositPokemonToPC); _lua.Globals["withdrawPokemonFromPC"] = new Func<int, int, bool>(WithdrawPokemonFromPC); _lua.Globals["swapPokemonFromPC"] = new Func<int, int, int, bool>(SwapPokemonFromPC); _lua.Globals["giveItemToPokemon"] = new Func<string, int, bool>(GiveItemToPokemon); _lua.Globals["takeItemFromPokemon"] = new Func<int, bool>(TakeItemFromPokemon); _lua.Globals["releasePokemonFromTeam"] = new Func<int, bool>(ReleasePokemonFromTeam); _lua.Globals["releasePokemonFromPC"] = new Func<int, int, bool>(ReleasePokemonFromPC); _lua.Globals["enablePrivateMessage"] = new Func<bool>(EnablePrivateMessage); _lua.Globals["disablePrivateMessage"] = new Func<bool>(DisablePrivateMessage); // Path functions _lua.Globals["pushDialogAnswer"] = new Action<int>(PushDialogAnswer); // General actions _lua.Globals["useItem"] = new Func<string, bool>(UseItem); _lua.Globals["useItemOnPokemon"] = new Func<string, int, bool>(UseItemOnPokemon); // Battle actions _lua.Globals["attack"] = new Func<bool>(Attack); _lua.Globals["weakAttack"] = new Func<bool>(WeakAttack); _lua.Globals["run"] = new Func<bool>(Run); _lua.Globals["sendUsablePokemon"] = new Func<bool>(SendUsablePokemon); _lua.Globals["sendAnyPokemon"] = new Func<bool>(SendAnyPokemon); _lua.Globals["sendPokemon"] = new Func<int, bool>(SendPokemon); _lua.Globals["useMove"] = new Func<string, bool>(UseMove); // Move learning actions _lua.Globals["forgetMove"] = new Func<string, bool>(ForgetMove); _lua.Globals["forgetAnyMoveExcept"] = new Func<DynValue[], bool>(ForgetAnyMoveExcept); try { TaskUtils.CallActionWithTimeout(() => _lua.DoString(_content), delegate { throw new Exception("The execution of the script timed out."); }, TimeoutDelay); } catch (SyntaxErrorException ex) { throw new Exception(ex.DecoratedMessage, ex); } }
private void ParseLuaCode(string script_body) { var t = Task.Run(() => { try { Script script = new Script(); script.Globals["debug"] = (Action<string>)printLog; script.Globals["delay"] = (Action<int>)Delay; script.Globals["toggle"] = (Func<int, int>)Toggle; script.Globals["pulse"] = (Func<int, int, int>)Pulse; script.Globals["wait_pin"] = (Func<int, int, int, int>)WaitPin; script.Globals["INT1"] = UtpPins.INT1; script.Globals["INT0"] = UtpPins.INT0; script.Globals["RX"] = UtpPins.RX; script.Globals["TX"] = UtpPins.TX; script.Globals["TRIAC"] = UtpPins.TRIAC; script.Globals["ZEROX"] = UtpPins.ZEROX; script.Globals["HIGH"] = UtpPinStates.HIGH; script.Globals["LOW"] = UtpPinStates.LOW; DynValue res = script.DoString(script_body); } catch (InterpreterException ex) { printLog(string.Format("Doh! An error occured! {0}", (ex.DecoratedMessage))); } }); }
public void ExecuteUserCode(string externalCode) { Logger.Info($"Executing user code {externalCode}"); MainScript.DoString(externalCode); }
private static void TableTestReverseWithTable() { string scriptCode = @" return dosum { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 } "; Script script = new Script(); script.Globals["dosum"] = (Func<Table, double>)Sum; DynValue res = script.DoString(scriptCode); Console.WriteLine(res.Number); }