public bool Awakening()
        {
            spaar.ModLoader.Game.OnSimulationToggle += GameOnOnSimulationToggle;
            spaar.ModLoader.Game.OnLevelWon         += GameOnOnLevelWon;
            env = new NLua.Lua();
            env.LoadCLRPackage();
            env["this"]       = this; // Give the script access to the gameobject.
            env["transform"]  = transform;
            env["gameObject"] = gameObject;
            env["enabled"]    = enabled;
            env["useAPI"]     = new Action(UseAPI);
            env["disableAPI"] = new Action(DisableAPI);

            if (Settings.useAPI)
            {
                Besiege.SetUp();
                env["besiege"] = Besiege._besiege;
            }
            try
            {
                env.DoString(source);
            }
            catch (NLua.Exceptions.LuaException e)
            {
                Debug.LogError(FormatException(e), context: gameObject);
                return(false);
            }
            Call("Awake");
            return(true);
        }
Beispiel #2
0
		public void TestBinaryLoadFile ()
		{
			using (Lua lua = new Lua ()) {
				lua.LoadCLRPackage ();
				if (IntPtr.Size == 4)
					lua.DoFile ("test_32.luac");
				else
					lua.DoFile ("test_64.luac");

				int width = (int)(double)lua ["width"];
				int height = (int)(double)lua ["height"];
				string message = (string)lua ["message"];
				int color_g	= (int)(double)lua ["color.g"];
				LuaFunction func = (LuaFunction)lua ["func"];
				object[] res = func.Call (12, 34);
				int x = (int)(double)res [0];
				int y = (int)(double)res [1];
				//function func(x,y)
				//	return x,x+y
				//end

				Assert.AreEqual (100, width);
				Assert.AreEqual (200, height);
				Assert.AreEqual ("Hello World!", message);
				Assert.AreEqual (20, color_g);
				Assert.AreEqual (12, x);
				Assert.AreEqual (46, y);
			}
		}
Beispiel #3
0
 public ScriptManager()
 {
     _scriptQueue = new Queue<Tuple<string, Entity, string>>();
     _lua = new Lua();
     SandboxVM();
     RegisterScriptMethods();
 }
Beispiel #4
0
        public Lua(Settings settings)
        {
            _settings = settings;
            NLua      = new NLua.Lua();

            SetupLua();
        }
Beispiel #5
0
 public LuaScriptContext()
 {
     Log.Write("debug", "Creating Lua script context");
     Lua = new Lua();
     Lua.HookException += OnLuaException;
     functionCache = new Cache<string, LuaFunction>(Lua.GetFunction);
 }
Beispiel #6
0
        private static void Main()
        {
            Console.Title = "NLua Test Environment";

            object x = 3;
            double y = (double)(int)x;

            string script = "function add(a, b) return a + b, a, b; end\n" +
                            "local function sub(a, b) return a - b; end\n" +
                            "local function mul(a, b) return a * b; end\n" +
                            "local function div(a, b) return a / b; end\n" +
                            "print(\"Adding 1 and 5 gives us \" .. add(1, 5));\n" +
                            "print(\"Subtracting 8 and 2 gives us \" .. sub(8, 2));\n" +
                            "print(\"Multiplying 32 and 1024 gives us \" .. mul(32, 1024));\n" +
                            "print(\"Dividing 8 and 2 gives us \" .. div(8, 2));\n";

            using (dynamic lua = new Lua())
            {
                lua.LoadStandardLibrary(LuaStandardLibraries.Basic);
                lua.DoString("print(\"This confirms the Lua environment has loaded the basic standard library.\\nThe Lua environment is operational.\");");
                lua.DoFile("TestScript.lua");

                lua.v = "test";

                object[] table = lua.x;
            }

            Console.ReadLine();
        }
Beispiel #7
0
 internal static string Execute(string content, CmdContext msg)
 {
     using (NLua.Lua lua = new NLua.Lua())
         using (PrintProxy proxy = new PrintProxy())
         {
             lua.RegisterFunction("print", proxy, proxy.GetType().GetMethod("Print", new Type[] { typeof(object[]) }));
             string code;
             using (StreamReader sr = new StreamReader(typeof(Lua).Assembly.GetManifestResourceStream("DuckBot.Resources.Sandbox.lua")))
                 code = sr.ReadToEnd();
             try
             {
                 const string template = "args = {...};rawText,sender,server,channel=args[1],args[2],args[3],args[4]\n";
                 string       source   = template + content;
                 using (LuaFunction func = (LuaFunction)lua.DoString(code, "sandbox")[0])
                 {
                     object[] rets = func.Call(source, msg.Args, msg.Sender, msg.Server, msg.Channel);
                     if (rets.Length >= 2)
                     {
                         object[] arr = new object[rets.Length - 1];
                         Array.Copy(rets, 1, arr, 0, arr.Length);
                         proxy.Print(arr);
                     }
                     string res = proxy.ToString().Trim();
                     return(res.Length == 0 ? msg.GetString("Strings.ret_empty_script") : res);
                 }
             }
             catch (NLua.Exceptions.LuaScriptException ex) { return(msg.GetString("err_generic") + ": " + ex.Message + "\n``` " + ex.Source + " ```"); }
         }
 }
        public bool Awakening()
        {
            spaar.ModLoader.Game.OnSimulationToggle += GameOnOnSimulationToggle;
            spaar.ModLoader.Game.OnLevelWon += GameOnOnLevelWon;
            env = new NLua.Lua();
            env.LoadCLRPackage();
            env["this"] = this; // Give the script access to the gameobject.
            env["transform"] = transform;
            env["gameObject"] = gameObject;
            env["enabled"] = enabled;
            env["useAPI"] = new Action(UseAPI);
            env["disableAPI"] = new Action(DisableAPI);

            if (Settings.useAPI)
            {
                Besiege.SetUp();
                env["besiege"] = Besiege._besiege;
            }
            try
            {
                env.DoString(source);
            }
            catch (NLua.Exceptions.LuaException e)
            {
                Debug.LogError(FormatException(e), context: gameObject);
                return false;
            }
            Call("Awake");
            return true;
        }
Beispiel #9
0
        public static void SetSandboxEnvironment(this NLua.Lua luaState)
        {
            var sb = $@"{{
{string.Join("\r\n", GetWhitelist().Select(identifier => $"  {identifier} = {identifier},"))}
{string.Join("\r\n", GetWhitelistTables().Select(table => $"  {table.First()} = {{ {string.Join(", ", table.Skip(1).Select(identifier => $"{identifier} = {table.First()}.{identifier}"))} }},"))}
}}";
        }
Beispiel #10
0
        public void Init()
        {
            if (IsInitialized)
                throw new InvalidOperationException("Already Initialized!");

            if (_state != null) _state.Dispose();
            
            _state = new Lua();
            _state.LoadCLRPackage();

            _state.DoString(@"luanet.load_assembly('WGestures.Core');
                              luanet.load_assembly('WindowsInput');
                              luanet.load_assembly('WGestures.Common');

                              GestureModifier=luanet.import_type('WGestures.Core.GestureModifier');  
                              VK=luanet.import_type('WindowsInput.Native.VirtualKeyCode');
                              Native=luanet.import_type('WGestures.Common.OsSpecific.Windows.Native');
                            ", "_init");

            _state["Input"] = Sim.Simulator;
            _state.RegisterFunction("ReportStatus", this, typeof(ScriptCommand).GetMethod("OnReportStatus"));

            if(InitScript != null)
            {
                DoString(InitScript, "Init");
            }
            
            IsInitialized = true;
        }
Beispiel #11
0
 /// <summary>
 /// Initialises a new instance of the LuaPlugin class
 /// </summary>
 /// <param name="filename"></param>
 internal LuaPlugin(string filename, NLua.Lua lua, FSWatcher watcher)
 {
     // Store filename
     Filename       = filename;
     LuaEnvironment = lua;
     this.watcher   = watcher;
 }
Beispiel #12
0
        public Spell(XmlNode xml, Lua lua)
            : base()
        {
            Name = xml.SelectSingleNode("name").InnerText;
            Desc = xml.SelectSingleNode("desc").InnerText;

            Type = (AttackType)Enum.Parse(typeof(AttackType), xml.SelectSingleNode("type").InnerText);
            Target = (BattleTarget)Enum.Parse(typeof(BattleTarget), xml.SelectSingleNode("target").InnerText);

            XmlNode targetsFirstNode = xml.SelectSingleNode("targetEnemiesFirst");
            TargetEnemiesFirst = targetsFirstNode == null ? true : Boolean.Parse(targetsFirstNode.InnerText);

            XmlNode costNode = xml.SelectSingleNode("cost");
            MPCost = costNode == null ? 0 : Int32.Parse(costNode.InnerText);

            XmlNode orderNode = xml.SelectSingleNode("order");
            Order = orderNode == null ? 0 : Int32.Parse(orderNode.InnerText);

            Elements = GetElements(xml.SelectNodes("elements/element")).ToArray();
            Statuses = GetStatusChanges(xml.SelectNodes("statusChange")).ToArray();

            Power = Int32.Parse(xml.SelectSingleNode("power").InnerText);
            Hitp = Int32.Parse(xml.SelectSingleNode("hitp").InnerText);

            XmlNode hitsNode = xml.SelectSingleNode("hits");
            Hits = hitsNode == null ? 1 : Int32.Parse(hitsNode.InnerText);

            DamageFormula = GetFormula(xml.SelectSingleNode("formula"), lua);
            HitFormula = GetHitFormula(xml.SelectSingleNode("hitFormula"), lua);
        }
Beispiel #13
0
	void Start()
	{
		lua = new NLua.Lua();
		lua.LoadCLRPackage();
		var method = typeof(Debug).GetMethod("Log", new Type[] { typeof(object) });
		lua.RegisterFunction("print", method);
	}
Beispiel #14
0
        protected LuaScript(Lua lua, TEntity entity, string tableName)
        {
            Lua    = lua;
            Entity = entity;

            _table = Lua.GetTable(tableName);
        }
Beispiel #15
0
        public static LuaTable MakeLuaTable(NLua.Lua luaInterpreter, string tableName)
        {
            luaInterpreter.NewTable(tableName);
            LuaTable taskTable = luaInterpreter.GetTable(tableName);

            return(taskTable);
        }
Beispiel #16
0
        public ScriptComponent()
        {
            Family = ComponentFamily.Script;

            lua = new Lua();
            lua.LoadCLRPackage();
        }
Beispiel #17
0
        private static void InitEditorState(Lua state)
        {
            state.LoadCLRPackage();

            string resName = "WorldSmith.Scripts.WorldsmithImports.lua";

            Assembly asm = Assembly.GetExecutingAssembly();
            using (System.IO.Stream s = asm.GetManifestResourceStream(resName))
            using (System.IO.StreamReader reader = new System.IO.StreamReader(s))
            {
                string data = reader.ReadToEnd();

                state.DoString(data, resName);               
            }

            state["Units"] = DotaData.AllUnits;          
            state["Heroes"] = DotaData.AllHeroes;          
            state["Abilities"] = DotaData.AllAbilities;           
            state["Items"] = DotaData.DefaultItems;
            state["Events"] = DotaData.Events;

            //Bind the DataClass enum
            state.DoString("DataClass = {}");
            state["DataClass.Default"] = DotaDataObject.DataObjectInfo.ObjectDataClass.Default;
            state["DataClass.Override"] = DotaDataObject.DataObjectInfo.ObjectDataClass.Override;
            state["DataClass.Custom"] = DotaDataObject.DataObjectInfo.ObjectDataClass.Custom;


        }
Beispiel #18
0
 public Task(Lua lua)
 {
     this.lua = lua;
       name = this.GetType ().Name.ToLower ();
       MethodInfo method = this.GetType ().GetMethod ("Run");
       All[name] = this;
       lua.RegisterFunction(name, this, method);
 }
Beispiel #19
0
        public API(Server server)
        {
            Server = server;
            Lua = new Lua();
            ScriptTimers = new List<ScriptTimer>();

            RegisterAllFunctions();
        }
Beispiel #20
0
		public static void SetLog(Lua lua)
		{
			if (PrintFunction == null)
				PrintFunction = new LuaNativeFunction(PrintWarning);
			
			LuaLib.LuaPushStdCallCFunction(lua.LuaState, PrintFunction);
			LuaLib.LuaSetGlobal(lua.LuaState, "log");
		}
Beispiel #21
0
 public static void SetPrint(Lua lua)
 {
     if (PrintFunction == null)
         PrintFunction = new LuaNativeFunction(Print);
     
     LuaLib.LuaPushStdCallCFunction(lua.LuaState, PrintFunction);
     LuaLib.LuaSetGlobal(lua.LuaState, "print");
 }
Beispiel #22
0
        static LuaHelper()
        {
            EditorState = new Lua();
           
            //GameState = new Lua();

            ScratchpadState = new Lua();
        }
Beispiel #23
0
        private static void PushVisibilityTable(NLua.Lua luaInterpreter)
        {
            luaInterpreter.NewTable("visibility");
            LuaTable luaTable = luaInterpreter.GetTable("visibility");

            luaTable["private"] = WorkshopItemVisibility.Private;
            luaTable["public"]  = WorkshopItemVisibility.Public;
        }
 static BuildingManager()
 {
     lua = new Lua();
     InitPaths = new Dictionary<string,string>();
     Buildings = new List<Building>();
     //Scan();
     //lua.
 }
Beispiel #25
0
 static void Main(string [] args)
 {
     using (var l = new Lua ()) {
         Action c = () => { Console.WriteLine ("Ola"); };
         l ["d"] = c;
         l.DoString (" d () ");
     }
 }
Beispiel #26
0
        public InitActions(Lua Lua, CombatSystem cSys, NameSystem nSys)
        {
            combatSystem = cSys;
            nameSystem = nSys;
            lua = Lua;

            Initialize();
        }
Beispiel #27
0
 public ArmorData(XmlNode node, Lua lua)
     : base(node, lua)
 {
     Defense = Int32.Parse(node.SelectSingleNode("def").InnerText);
     DefensePercent = Int32.Parse(node.SelectSingleNode("defp").InnerText);
     MagicDefense = Int32.Parse(node.SelectSingleNode("mdf").InnerText);
     MagicDefensePercent = Int32.Parse(node.SelectSingleNode("mdfp").InnerText);
 }
Beispiel #28
0
 public VsErcPackage()
 {
     instance = this;
     this.vsHelper = new VsHelper(this);
     this.vsErcLogger = new VsErcLogger(this);
     this.lua = new Lua();
     this.vsErcBindings = new VsErcBindings(this, VsErcBindings.DefaultErcFilePath);
 }
Beispiel #29
0
 /// <summary>
 /// 新しくLuaシーンを初期化。
 /// </summary>
 /// <param name="sceneName">シーン名</param>
 /// <param name="luafile">制御するLuaのファイル名</param>
 public LuaScene(string sceneName, string luafile)
     : base()
 {
     LuaScript = new Lua();
     LuaScript["Scenes"] = Scenes.Instance;
     LuaScript.DoFile(luafile);
     ID = sceneName;
 }
Beispiel #30
0
        public static void RegisterNLuaBox(Lua context)
        {
            context.RegisterLuaDelegateType (typeof (EventHandler<EventArgs>), typeof (LuaEventArgsHandler));
            context.RegisterLuaDelegateType (typeof (EventHandler), typeof (LuaEventArgsHandler));
            context.RegisterLuaDelegateType (typeof (EventHandler<UIButtonEventArgs>), typeof (LuaButtonEventArgsHandler));

            context.RegisterLuaClassType (typeof (UIViewController), typeof (NLuaBoxUIViewControllerBinder));
        }
Beispiel #31
0
        public Item(XmlNode node, Lua lua)
            : this()
        {
            Name = node.SelectSingleNode("name").InnerText;
            Description = node.SelectSingleNode("desc").InnerText;

            XmlNode field = node.SelectSingleNode("field");

            if (field != null)
            {
                FieldUsage = new FieldUsageRecord();

                FieldUsage.Target = (FieldTarget)Enum.Parse(typeof(FieldTarget), field.SelectSingleNode("@target").Value);

                char targetParameterName = Char.ToLower(FieldUsage.Target.ToString()[0]);

                string canUse = String.Format("return function ({0}) {1} end", targetParameterName, field.SelectSingleNode("canUse").InnerText);
                string use = String.Format("return function ({0}) {1} end", targetParameterName, field.SelectSingleNode("use").InnerText);

                try
                {
                    FieldUsage.CanUse = (LuaFunction)lua.DoString(canUse).First();
                    FieldUsage.Use = (LuaFunction)lua.DoString(use).First();
                }
                catch (Exception e)
                {
                    throw new ImplementationException("Error in item field scripts; id = " + ID, e);
                }
            }

            XmlNode battle = node.SelectSingleNode("battle");

            if (battle != null)
            {
                BattleUsage = new BattleUsageRecord();

                BattleUsage.Target = (BattleTarget)Enum.Parse(typeof(BattleTarget), battle.SelectSingleNode("@target").Value);

                XmlNode intendedForEnemiesNode = battle.SelectSingleNode("@intendedForEnemies");

                if (intendedForEnemiesNode != null)
                {
                    BattleUsage.IntendedForEnemies = Boolean.Parse(intendedForEnemiesNode.Value);
                }

                string use = String.Format("return function (s, t) {0} end", battle.SelectSingleNode("use").InnerText);

                try
                {
                    BattleUsage.Use = (LuaFunction)lua.DoString(use).First();
                }
                catch (Exception e)
                {
                    throw new ImplementationException("Error in item battle scripts; id = " + ID, e);
                }
            }
        }
Beispiel #32
0
 public BubbleLua(Lua lua, bool init = true)
 {
     Lua = lua;
     if (!init)
         return;
     Lua.NewTable ("bubble");
     Bubble = (LuaTable)Lua ["bubble"];
     lua.DoString (EmbeddedResources.GetString ("BubbleEngine.LuaAPI.bubbleinternal.lua"));
 }
Beispiel #33
0
        public void TestBasicFunctionality()
        {
            Lua lua = new Lua();

            ////
            //TestLuaFunctions testLuaFunctions = new TestLuaFunctions();
            //lua.RegisterFunction("Say", testLuaFunctions, testLuaFunctions.GetType().GetMethod("Say"));
            //lua.RegisterFunction("CreateInstance", typeof(TestLuaFunctions).GetMethod("CreateInstance"));
            //lua.DoString("Say('pouet')");
            //lua.DoString("instance = CreateInstance()");
            //lua.DoString("instance:Say('woohoo')");

            //TestLuaFunctions externalInstance = (TestLuaFunctions) lua["instance"];
            //externalInstance.Say("using externally created instance to call Say");

            //
            CreateWorld();

            ITestCharacter testCharacter = TestCharacter.Create();

            lua["testcharacter"] = testCharacter;

            lua.RegisterFunction("print", typeof(LuaOutput).GetMethod("Print"));
            //lua["this"] = bigBadMob;
            //lua["room"] = DependencyContainer.Instance.GetInstance<IWorld>().Rooms.First();
            lua.RegisterFunction("getCharacter", this, GetType().GetMethod("GetCharacter"));
            lua.DoString(
                @"print('this is a debug message')
            local this = getCharacter()
            cName = this.DisplayName
            function luanet.each(o)
               local e = o:GetEnumerator()
               return function()
                  if e:MoveNext() then
                    return e.Current
                 end
               end
            end

            local each = luanet.each;
            for c in each(this.Room.People) do
                local name = c == getCharacter() and 'me' or c.DisplayName;
                print('in room:'..name);
            end

           -- local globals = _G
            --for g in each(globals) do
            --    print('global:'..tostring(g));
            --end");
            //doesn't work    lua.DoString("function this.pouet(s) print(s) end");
            var cName          = lua["cName"];
            var luanet         = lua["luanet"];
            var globals        = lua["_G"];
            var testCharacter2 = lua["testcharacter"];

            lua.Close();
        }
Beispiel #34
0
        public void Dispose()
        {
            if (Lua == null)
                return;

            GC.SuppressFinalize(this);
            Lua.Dispose();
            Lua = null;
        }
        private static void AddSetting(Lua lua, ModSetting setting)
        {
            var path = "settings.startup." + setting.Name;

            lua.NewTable(path);
            var table = lua.GetTable(path);

            table["value"] = setting.DefaultValue;
        }
Beispiel #36
0
        public EnemyGenerator(Lua Lua, CombatSystem cSys, EntityManager eMan)
        {
            combatSystem = cSys;
            entityManager = eMan;
            lua = Lua;

            RegisterLuaFunctions();

            instance = this;
        }
Beispiel #37
0
        void Start()
        {
			LuaState = new Lua();
			LuaState.LoadUnityExpand();
			LuaState.LoadImportExpand();
			LuaState.LoadCLRPackage("Using");

			LuaState.CallLunaFunction("lunatest.lua", "Start", this.gameObject);
			LuaState.CheckStack();
        }
Beispiel #38
0
		static void Main (string [] args)
		{
			using (var l = new Lua ()) {
				l.LoadCLRPackage ();
				l.DoString (" import ('ConsoleTest') ");
				l.DoString (@"
						Program.Method (1)
				");
			}
		}
Beispiel #39
0
        private static LuaTable CreateConfigurationTableWithOnlyTags(NLua.Lua luaInterpreter)
        {
            LuaTable table = NLuaUtilities.MakeLuaTable(luaInterpreter, "the_table");
            LuaTable tags  = NLuaUtilities.MakeLuaTable(luaInterpreter, "tag_table");

            tags[0]       = "EAW";
            tags[1]       = "FOC";
            table["tags"] = tags;
            return(table);
        }
Beispiel #40
0
 public static void InitializeState()
 {
     L               = new NLua.Lua();
     L["Controls"]   = new Library.Controls();
     L["System"]     = new Library.SilverSystem();
     L["Units"]      = new Library.Units();
     L["Forms"]      = new Library.Forms();
     L["FS"]         = new Library.FS();
     L["Networking"] = new Library.Networking();
 }
Beispiel #41
0
 public static void SetReadFile(Lua lua)
 {
     if (ReadFileFunction == null)
         ReadFileFunction = new LuaNativeFunction(ReadFile);
     
     LuaLib.LuaGetGlobal(lua.LuaState, "io");
     LuaLib.LuaPushString(lua.LuaState, "readfile");
     LuaLib.LuaPushStdCallCFunction(lua.LuaState, ReadFileFunction);
     LuaLib.LuaSetTable(lua.LuaState, -3);
     LuaLib.LuaPop(lua.LuaState, 1);
 }
Beispiel #42
0
        /// <summary>
        /// Initialises the Lua environment
        /// </summary>
        private void InitialiseLua()
        {
            // Create the Lua environment
            LuaEnvironment = new NLua.Lua();

            // Filter useless or potentially malicious libraries/functions
            LuaEnvironment["os"]      = null;
            LuaEnvironment["io"]      = null;
            LuaEnvironment["require"] = null;
            LuaEnvironment["dofile"]  = null;
            LuaEnvironment["package"] = null;
            LuaEnvironment["luanet"]  = null;
            LuaEnvironment["load"]    = null;

            // Read util methods
            setmetatable = LuaEnvironment["setmetatable"] as LuaFunction;

            // Create metatables
            //Type mytype = GetType();
            LuaEnvironment.NewTable("tmp");
            overloadselectormeta = LuaEnvironment["tmp"] as LuaTable;
            //LuaEnvironment.RegisterFunction("tmp.__index", mytype.GetMethod("FindOverload", BindingFlags.Public | BindingFlags.Static));
            LuaEnvironment.NewTable("tmp");
            // Ideally I'd like for this to be implemented C# side, but using C#-bound methods as metamethods seems dodgy
            LuaEnvironment.LoadString(
                @"function tmp:__index( key )
    local sftbl = rawget( self, '_sftbl' )
    local field = sftbl[ key ]
    if (field) then return field:GetValue( nil ) end
end
function tmp:__newindex( key, value )
    local sftbl = rawget( self, '_sftbl' )
    local field = sftbl[ key ]
    if (field) then field:SetValue( nil, value ) end
end
", "LuaExtension").Call();
            //LuaEnvironment.RegisterFunction("tmp.__index", mytype.GetMethod("ReadStaticProperty", BindingFlags.NonPublic | BindingFlags.Static));
            //LuaEnvironment.RegisterFunction("tmp.__newindex", mytype.GetMethod("WriteStaticProperty", BindingFlags.NonPublic | BindingFlags.Static));
            typetablemeta         = LuaEnvironment["tmp"] as LuaTable;
            LuaEnvironment["tmp"] = null;

            // Bind all namespaces and types
            foreach (var type in AppDomain.CurrentDomain.GetAssemblies()
                     .Where(AllowAssemblyAccess)
                     .SelectMany(Utility.GetAllTypesFromAssembly)
                     .Where(AllowTypeAccess))
            {
                // Get the namespace table
                LuaTable nspacetable = GetNamespaceTable(Utility.GetNamespace(type));

                // Bind the type
                nspacetable[type.Name] = CreateTypeTable(type);
            }
        }
Beispiel #43
0
        GivenLuaUpdateSteamWorkshopItemTaskWithConfigTable_With_PrivateVisibility__OnCreation__ShouldConfigureTask()
        {
            TaskBuilderMock taskBuilderMock = CreateTaskBuilderMock(WorkshopItemVisibility.Private);

            using NLua.Lua luaInterpreter = new NLua.Lua();
            PushVisibilityTable(luaInterpreter);
            LuaTable table = CreateConfigurationTable(luaInterpreter, LuaPrivateVisibility);
            LuaUpdateSteamWorkshopItemTask sut = new LuaUpdateSteamWorkshopItemTask(taskBuilderMock, table);

            taskBuilderMock.Verify();
        }
Beispiel #44
0
        public ScriptTrigger(Lua luaState, IZone zone, Script tringgerScript, IEnumerable <Entity> entities)
        {
            Zone = zone;
            luaState.DoString(tringgerScript.Text);
            _onInActionLua  = luaState["OnInAction"]  as LuaFunction;
            _onOutActionLua = luaState["OnOutAction"] as LuaFunction;
            _entities       = entities;
            _inside         = _entities.ToDictionary(x => x, zone.IsInside);

            ScriptingAPI.I.Core.Log.Info($"[Script] Loaded trigger script \"{tringgerScript.Path}.lua\".");
        }
Beispiel #45
0
		public void Setup()
		{
			lua = new Lua ();
			lua.RegisterFunction ("WriteLineString", typeof (Console).GetMethod ("WriteLine", new Type [] { typeof (String) }));
			
			lua.DoString (@"
			function print (param)
				WriteLineString (tostring(param))
			end
			");
		}
Beispiel #46
0
        public void GivenLuaJobWithJob__WhenCallingAddTasksWithNonTaskValue__ShouldThrowLuaScriptException()
        {
            using NLua.Lua luaInterpreter = new NLua.Lua();
            LuaTable invalidTable = MakeLuaTable(luaInterpreter, "invalidTable");

            invalidTable[1] = "Invalid";

            JobStub jobStub = new JobStub();
            LuaJob  sut     = new LuaJob(jobStub);

            sut.add_tasks(invalidTable);
        }
Beispiel #47
0
        GivenLuaUpdateSteamWorkshopItemTaskWithConfigTable_With_Tags__OnCreation__ShouldConfigureTaskWithTags()
        {
            TaskBuilderSpy taskBuilderSpy = new TaskBuilderSpy();

            using NLua.Lua luaInterpreter = new NLua.Lua();
            LuaTable table = CreateConfigurationTableWithOnlyTags(luaInterpreter);

            LuaUpdateSteamWorkshopItemTask sut = new LuaUpdateSteamWorkshopItemTask(taskBuilderSpy, table);

            object actual = taskBuilderSpy["Tags"];

            Assert.IsInstanceOfType(actual, typeof(IEnumerable <string>));
            CollectionAssert.AreEquivalent(ExpectedTags, ((IEnumerable <string>)actual).ToArray());
        }
        public CustomCommandProvider(AldertoDbContext context)
        {
            _context  = context;
            _luaState = new NLua.Lua();
            _commands = new Dictionary <string, LuaFunction>();

            // Load Lua code
            // TODO: Load lua code. Uncomment below
            //_luaState.LoadCLRPackage();
            //_luaState.DoString("import ('Alderto.Bot', 'Alderto.Bot.Commands')");

            // Prevent additional namespaces to be added
            _luaState.DoString("import = function () end");
        }
Beispiel #49
0
        /// <summary>
        /// Translates a single object from its C# form to its Lua form
        /// </summary>
        /// <param name="lua"></param>
        /// <param name="item"></param>
        /// <returns></returns>
        private static object TranslateConfigItemToLuaItem(NLua.Lua lua, object item)
        {
            // Switch on the object type
            if (item is int || item is float || item is double)
            {
                return(Convert.ToDouble(item));
            }
            else if (item is bool)
            {
                return(Convert.ToBoolean(item));
            }
            else if (item is string)
            {
                return(item);
            }
            else if (item is List <object> )
            {
                lua.NewTable("tmplist");
                var tbl = lua["tmplist"] as LuaTable;
                lua["tmplist"] = null;

                var list = item as List <object>;
                for (var i = 0; i < list.Count; i++)
                {
                    tbl[i + 1] = TranslateConfigItemToLuaItem(lua, list[i]);
                }

                return(tbl);
            }
            else
            {
                if (item is Dictionary <string, object> )
                {
                    lua.NewTable("tmpdict");
                    var tbl = lua["tmpdict"] as LuaTable;
                    lua["tmpdict"] = null;

                    var dict = item as Dictionary <string, object>;
                    foreach (var pair in dict)
                    {
                        CreateFullPath(pair.Key, tbl, lua);
                        tbl[pair.Key] = TranslateConfigItemToLuaItem(lua, pair.Value);
                    }

                    return(tbl);
                }
                return(null);
            }
        }
Beispiel #50
0
        private static LuaTable CreateConfigurationTable(NLua.Lua luaInterpreter, string luaVisibility)
        {
            LuaTable table = NLuaUtilities.MakeLuaTable(luaInterpreter, "the_table");
            WorkshopItemVisibility visibility =
                (WorkshopItemVisibility)luaInterpreter.GetObjectFromPath("visibility." + luaVisibility);

            table["app_id"]           = AppIdAsLong;
            table["item_id"]          = ItemIdAsLong;
            table["title"]            = Title;
            table["description_file"] = DescriptionFilePath;
            table["item_folder"]      = FolderPath;
            table["visibility"]       = visibility;
            table["language"]         = Language;
            return(table);
        }
Beispiel #51
0
        private static void CreateFullPath(string fullPath, LuaTable tbl, NLua.Lua lua)
        {
            var path = fullPath.Split('.');

            for (var i = 0; i < path.Length - 1; i++)
            {
                if (tbl[path[i]] == null)
                {
                    lua.NewTable("tmp");
                    var table = (LuaTable)lua["tmp"];
                    tbl[path[i]] = table;
                    lua["tmp"]   = null;
                    tbl          = table;
                }
            }
        }
Beispiel #52
0
        public static void RemoveNonWhitelistedGlobals(this NLua.Lua luaState)
        {
            var globalsTable = (LuaTable)luaState["_G"];

            var whitelist       = GetWhitelist().ToHashSet();
            var whitelistTables = GetWhitelistTables().ToDictionary(table => table.First(), table => table.Skip(1).ToHashSet());

            foreach (string key in globalsTable.Keys)
            {
                if (whitelist.Contains(key))
                {
                    whitelist.Remove(key);
                }
                else if (whitelistTables.ContainsKey(key))
                {
                    foreach (string tableKey in ((LuaTable)luaState[key]).Keys)
                    {
                        if (whitelistTables[key].Contains(tableKey))
                        {
                            whitelistTables[key].Remove(tableKey);
                        }
                        else
                        {
                            luaState[$"{key}.{tableKey}"] = null;
                        }
                    }

                    if (whitelistTables[key].Any())
                    {
                        throw new Exception("Table whitelist contains invalid members.");
                    }

                    whitelistTables.Remove(key);
                }
                else
                {
                    luaState[key] = null;
                }
            }

            if (whitelist.Any() || whitelistTables.Any())
            {
                throw new Exception("Whitelist contains invalid members");
            }
        }
Beispiel #53
0
        /// <summary>
        /// Copies and translates the contents of the specified config file into the specified table
        /// </summary>
        /// <param name="config"></param>
        /// <param name="lua"></param>
        /// <returns></returns>
        public static LuaTable TableFromConfig(DynamicConfigFile config, NLua.Lua lua)
        {
            // Make a table
            lua.NewTable("tmp");
            LuaTable tbl = lua["tmp"] as LuaTable;

            lua["tmp"] = null;

            // Loop each item in config
            foreach (var pair in config)
            {
                // Translate and set on table
                tbl[pair.Key] = TranslateConfigItemToLuaItem(lua, pair.Value);
            }

            // Return
            return(tbl);
        }
Beispiel #54
0
        /// <summary>
        /// A label for displaying values obtained through Lua scripts.
        /// </summary>
        /// <param name="filePath">The path to the Lua script. The script must contain a GetValue() function, which returns the desired text to be displayed.</param>
        /// <param name="lua">Obtained by calling GetLua() on a WatchManager32Bit.</param>
        public LuaWatch(string filePath, Lua.Lua lua)
        {
            NLua.Lua n = new NLua.Lua();
            n.LoadCLRPackage();
            n.DoString("import ('DeSmuME_Watch', 'DeSmuME_Watch.Lua')");

            n.DoFile(filePath);
            luaGetValue = n.GetFunction("GetValue");
            this.lua    = lua;
            n["WATCH"]  = lua;

            if (luaGetValue == null)
            {
                throw new Exception("Lua script could not be loaded. Make sure it contains the function GetValue().");
            }

            this.AutoSize = true;
            this.SetText("?");
        }
        public static object ValueToLua(NLua.Lua lua, object value)
        {
            if (value is bool)
            {
                return(value);
            }
            if (value is Color c)
            {
                // var table = lua.NewTable();

                var r = c.R;
                var g = c.G;
                var b = c.B;
                var a = c.A;

                // todo: I don't really know the best way to do this
                return(lua.DoString($"return [{r}, {g}, {b}, {a}]")[0]);
            }

            throw new Exception(nameof(Value));
        }
        public static object ValueToClr(NLua.Lua lua, object value)
        {
            if (value is bool)
            {
                return(value);
            }
            if (value is LuaTable table && table.IsArray())
            {
                var list = table.ToList();
                if (list.HasDefinedType(out var type))
                {
                    if (type == typeof(long) || type == typeof(double))
                    {
                        return(new Color(list.Cast <double>()));
                    }
                }
            }

            if (value is int)
            {
                return(value);
            }
            if (value is long)
            {
                return(value);
            }
            if (value is double)
            {
                return(value);
            }
            if (value is string)
            {
                return(value);
            }

            throw new Exception($"{nameof(Value)} is {value.GetType()}");
        }
Beispiel #57
0
 /// <summary>
 /// Run the specified script.
 /// </summary>
 /// <param name="scriptFile">Script file name</param>
 public void RunScript(string scriptFile)
 {
     if (File.Exists(scriptFile))
     {
         try
         {
             using (NLua.Lua lua = new NLua.Lua())
             {
                 lua.LoadCLRPackage();
                 _luaAPI.RegisterFunctions(lua);
                 lua.DoFile(scriptFile);
                 LuaFunction fnc = lua.GetFunction("on_Run");
                 if (fnc != null)
                 {
                     fnc.Call();
                 }
             }
         }
         catch (LuaScriptException e)
         {
             MessageBox.Show(e.Message, Resources.ScriptException, MessageBoxButtons.OK);
         }
     }
 }
Beispiel #58
0
        public void GivenLuaJobWithJob__WhenCallingAddTasks__ContainedJobShouldHaveAllTasks()
        {
            using NLua.Lua luaInterpreter = new NLua.Lua();

            TaskDummy firstTaskDummy  = new TaskDummy();
            TaskDummy secondTaskDummy = new TaskDummy();

            LuaTable taskTable = MakeLuaTable(luaInterpreter, "taskTable");

            taskTable[1] = new LuaTaskStub {
                Task = firstTaskDummy
            };
            taskTable[2] = new LuaTaskStub {
                Task = secondTaskDummy
            };

            JobStub jobStub = new JobStub();
            LuaJob  sut     = new LuaJob(jobStub);

            sut.add_tasks(taskTable);

            ITask[] expectedTasks = { firstTaskDummy, secondTaskDummy };
            CollectionAssert.AreEqual(expectedTasks, jobStub.Tasks);
        }
 public LuaScriptEngine()
 {
     _lua = new NLua.Lua();
 }
Beispiel #60
0
        /// <summary>
        /// Initializes the Lua environment
        /// </summary>
        private void InitializeLua()
        {
            // Create the Lua environment
            LuaEnvironment = new NLua.Lua();

            // Filter useless or potentially malicious libraries/functions
            LuaEnvironment["os"]      = null;
            LuaEnvironment["io"]      = null;
            LuaEnvironment["require"] = null;
            LuaEnvironment["dofile"]  = null;
            LuaEnvironment["package"] = null;
            LuaEnvironment["luanet"]  = null;
            LuaEnvironment["load"]    = null;

            // Read util methods
            setmetatable = LuaEnvironment["setmetatable"] as LuaFunction;

            // Create metatables
            //Type mytype = GetType();
            LuaEnvironment.NewTable("tmp");
            overloadselectormeta = LuaEnvironment["tmp"] as LuaTable;
            //LuaEnvironment.RegisterFunction("tmp.__index", mytype.GetMethod("FindOverload", BindingFlags.Public | BindingFlags.Static));
            LuaEnvironment.NewTable("tmp");
            // Ideally I'd like for this to be implemented C# side, but using C#-bound methods as metamethods seems dodgy
            LuaEnvironment.LoadString(
                @"function tmp:__index( key )
    local sftbl = rawget( self, '_sftbl' )
    local field = sftbl[ key ]
    if (field) then return field:GetValue( nil ) end
end
function tmp:__newindex( key, value )
    local sftbl = rawget( self, '_sftbl' )
    local field = sftbl[ key ]
    if (field) then field:SetValue( nil, value ) end
end
", "LuaExtension").Call();
            //LuaEnvironment.RegisterFunction("tmp.__index", mytype.GetMethod("ReadStaticProperty", BindingFlags.NonPublic | BindingFlags.Static));
            //LuaEnvironment.RegisterFunction("tmp.__newindex", mytype.GetMethod("WriteStaticProperty", BindingFlags.NonPublic | BindingFlags.Static));
            typetablemeta         = LuaEnvironment["tmp"] as LuaTable;
            LuaEnvironment["tmp"] = null;

            LuaEnvironment.NewTable("tmp");
            LuaEnvironment.LoadString(
                @"function tmp:__index( key )
    if (type( key ) == 'table') then
        local baseType = rawget( self, '_type' )
        return util.SpecializeType( baseType, key )
    end
end
", "LuaExtension").Call();
            generictypetablemeta  = LuaEnvironment["tmp"] as LuaTable;
            LuaEnvironment["tmp"] = null;

            LuaEnvironment.NewTable("libraryMetaTable");
            LuaEnvironment.LoadString(
                @"function libraryMetaTable:__index( key )
    local ptbl = rawget( self, '_properties' )
    local property = ptbl[ key ]
    if (property) then return property:GetValue( rawget( self, '_object' ), null ) end
end
function libraryMetaTable:__newindex( key, value )
    local ptbl = rawget( self, '_properties' )
    local property = ptbl[ key ]
    if (property) then property:SetValue( rawget( self, '_object' ), value ) end
end
", "LuaExtension").Call();
            libraryMetaTable = LuaEnvironment["libraryMetaTable"] as LuaTable;
            LuaEnvironment["libraryMetaTable"] = null;

            LuaEnvironment.NewTable("tmp");
            PluginMetatable = LuaEnvironment["tmp"] as LuaTable;
            LuaEnvironment.LoadString(
                @"function tmp:__newindex( key, value )
    if (type( value ) ~= 'function') then return rawset( self, key, value ) end
    local activeAttrib = rawget( self, '_activeAttrib' )
    if (not activeAttrib) then return rawset( self, key, value ) end
    if (activeAttrib == self) then
        print( 'PluginMetatable.__newindex - self._activeAttrib was somehow self!' )
        rawset( self, key, value )
        return
    end
    local attribArr = rawget( self, '_attribArr' )
    if (not attribArr) then
        attribArr = {}
        rawset( self, '_attribArr', attribArr )
    end
    activeAttrib._func = value
    attribArr[#attribArr + 1] = activeAttrib
    rawset( self, '_activeAttrib', nil )
end
", "LuaExtension").Call();
            LuaEnvironment["tmp"] = null;
        }