From b02a9a188db188952026fe9683e8d62ffec8088b Mon Sep 17 00:00:00 2001 From: abcdefg30 Date: Fri, 8 Apr 2016 11:00:19 +0200 Subject: [PATCH] Add a Utils.Where function to lua for filtering collections --- .../Scripting/Global/UtilsGlobal.cs | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/OpenRA.Mods.Common/Scripting/Global/UtilsGlobal.cs b/OpenRA.Mods.Common/Scripting/Global/UtilsGlobal.cs index 66fa9f4fdd..50ca3e5add 100644 --- a/OpenRA.Mods.Common/Scripting/Global/UtilsGlobal.cs +++ b/OpenRA.Mods.Common/Scripting/Global/UtilsGlobal.cs @@ -9,6 +9,7 @@ */ #endregion +using System.Collections; using System.Linq; using Eluant; using OpenRA.Scripting; @@ -54,6 +55,20 @@ namespace OpenRA.Mods.Common.Scripting return true; } + [Desc("Returns the original collection filtered with the func.")] + public LuaTable Where(LuaValue[] collection, LuaFunction func) + { + var t = Context.CreateTable(); + + foreach (var c in collection) + using (var ret = func.Call(c)) + using (var result = ret.FirstOrDefault()) + if (result != null && result.ToBoolean()) + t.Add(t.Count + 1, c); + + return t; + } + [Desc("Returns the first n values from a collection.")] public LuaValue[] Take(int n, LuaValue[] source) {