private static Dictionary <string, Double> luaOrderTable2DictionaryDouble(LuaTable lTable) { Dictionary <string, Double> ht = new Dictionary <string, Double>(); //probably any mod can do its custom format for the order config file //but the standard seems to be to return two tables ("order" and "data"); //CA uses a dedicated order file returning the order table directly (like in older spring) LuaTable orderTab = (LuaTable)lTable.GetValue("order"); LuaTable dataTab = (LuaTable)lTable.GetValue("data"); if (orderTab != null && dataTab != null) { //we have standard format IDictionaryEnumerator ienum = (IDictionaryEnumerator)orderTab.GetEnumerator(); while (ienum.MoveNext()) { ht.Add((String)ienum.Key, (Double)ienum.Value); } } else { //we have CA-format: dedicated order file IDictionaryEnumerator ienum = (IDictionaryEnumerator)lTable.GetEnumerator(); while (ienum.MoveNext()) { ht.Add((String)ienum.Key, (Double)ienum.Value); } } return(ht); }
public static LuaValue concat(LuaValue[] values) { LuaTable table = values[0] as LuaTable; LuaString separator = values.Length > 1 ? values[1] as LuaString : LuaString.Empty; LuaNumber startNumber = values.Length > 2 ? values[2] as LuaNumber : null; LuaNumber endNumber = values.Length > 3 ? values[3] as LuaNumber : null; int start = startNumber == null ? 1 : (int)startNumber.Number; int end = endNumber == null ? table.Length : (int)endNumber.Number; if (start > end) { return(LuaString.Empty); } else { StringBuilder text = new StringBuilder(); for (int index = start; index < end; index++) { text.Append(table.GetValue(index).ToString()); text.Append(separator.Text); } text.Append(table.GetValue(end).ToString()); return(new LuaString(text.ToString())); } }
private static void AddChildControls(object control, LuaTable table) { ToolStrip toolStrip = control as ToolStrip; if (toolStrip != null) { foreach (var item in table.Keys) { try { toolStrip.Items.Add((ToolStripItem)table.GetValue(item).Value); } catch (Exception) { } } return; } SplitContainer splitContainer = control as SplitContainer; if (splitContainer != null) { splitContainer.Panel1.Controls.Add((Control)table.GetValue(1).Value); splitContainer.Panel2.Controls.Add((Control)table.GetValue(2).Value); return; } Control container = control as Control; foreach (var item in table.Keys) { try { container.Controls.Add((Control)table.GetValue(item).Value); } catch (Exception) { } } }
/// <summary> /// Executes the chunk /// </summary> /// <param name="enviroment">The environment to run in</param> /// <param name="isBreak">whether to break execution</param> /// <returns></returns> public override LuaValue Execute(LuaTable enviroment, out bool isBreak) { LuaTable table = enviroment; if (this.Name.MethodName == null) { for (int i = 0; i < this.Name.FullName.Count - 1; i++) { LuaValue obj = enviroment.GetValue(this.Name.FullName[i]); table = obj as LuaTable; if (table == null) { throw new Exception("Not a table: " + this.Name.FullName[i]); } } table.SetNameValue( this.Name.FullName[this.Name.FullName.Count - 1], this.Body.Evaluate(enviroment)); } else { for (int i = 0; i < this.Name.FullName.Count; i++) { LuaValue obj = enviroment.GetValue(this.Name.FullName[i]); if ((obj as LuaClass) != null) { table = (obj as LuaClass).Self; } else { table = obj as LuaTable; } if (table == null) { throw new Exception("Not a table: " + this.Name.FullName[i]); } } this.Body.ParamList.NameList.Insert(0, "self"); table.SetNameValue( this.Name.MethodName, this.Body.Evaluate(enviroment)); } isBreak = false; return(null); }
public static LuaValue GetControlCreator(LuaValue[] values) { LuaString typeString = values[0] as LuaString; string typeName = "System.Windows.Forms." + typeString.Text; Type type = Assembly.GetAssembly(typeof(Application)).GetType(typeName, true, true); LuaFunction func = new LuaFunction((LuaValue[] args) => { object control = Activator.CreateInstance(type); LuaTable table = args[0] as LuaTable; string name = null; if (table.Count > 0) { AddChildControls(control, table); } if (table.Count > 0) { foreach (var pair in table.KeyValuePairs) { string member = (pair.Key as LuaString).Text; if (member == "Name") { name = (string)pair.Value.Value; continue; } SetMemberValue(control, type, member, pair.Value.Value); } } LuaUserdata data = new LuaUserdata(control); data.MetaTable = GetControlMetaTable(); if (name != null) { LuaTable enviroment = currentModule.GetValue("_G") as LuaTable; enviroment.SetNameValue(name, data); } return(data); } ); currentModule.SetNameValue(typeString.Text, func); return(func); }
/// <summary> /// Gets the value of a field in a Lua table element. /// </summary> /// <returns>The field value as a Lua.Result. To get a basic data type, addend <c>.AsString</c>, <c>.AsBool</c>, etc., to it.</returns> /// <param name="table">Table name.</param> /// <param name="element">Name of an element in the table.</param> /// <param name="field">Name of a field in the element.</param> public static Lua.Result GetTableField(string table, string element, string field) { LuaTable luaTable = Lua.Environment.GetValue(table) as LuaTable; if (luaTable == null) { return(Lua.NoResult); } LuaTable elementTable = luaTable.GetValue(StringToTableIndex(element)) as LuaTable; if (elementTable == null) { return(Lua.NoResult); } LuaValue luaValue = elementTable.GetValue(StringToTableIndex(field)); return((luaValue != null && luaValue != LuaNil.Nil) ? new Lua.Result(luaValue) : Lua.NoResult); //--- Was (unoptimized): //string tableIndex = StringToTableIndex(element); //LuaTableWrapper luaTable = SafeGetLuaResult(string.Format("return {0}", new System.Object[] { table })).AsTable; //if (luaTable == null) return Lua.NoResult; //foreach (var o in luaTable.Keys) { // if ((o.GetType() == typeof(string)) && (string.Equals((string) o, tableIndex))) { // return SafeGetLuaResult(string.Format("return {0}[\"{1}\"].{2}", new System.Object[] { table, tableIndex, StringToTableIndex(field) })); // } //} //return Lua.NoResult; }
private static LuaFunction GetMetaFunction(string name, LuaValue leftValue, LuaValue rightValue) { LuaTable left = leftValue as LuaTable; if (left != null) { LuaFunction func = left.GetValue(name) as LuaFunction; if (func != null) { return(func); } } LuaFunction f = leftValue.MetaTable.GetValue(name) as LuaFunction; if (f != null) { return(f); } LuaTable right = rightValue as LuaTable; if (right != null) { return(right.GetValue(name) as LuaFunction); } f = rightValue.MetaTable.GetValue(name) as LuaFunction; if (f != null) { return(f); } return(null); }
/// <summary> /// Gets the value of a variable in the Lua Variable table. /// </summary> /// <returns>The variable value as a Lua.Result. To get a basic data type, addend <c>.AsString</c>, <c>.AsBool</c>, etc., to it.</returns> /// <param name="variable">Variable name.</param> /// <example><code>int numKills = GetVariable("Kills").AsInt</code></example> public static Lua.Result GetVariable(string variable) { LuaTable luaTable = Lua.Environment.GetValue("Variable") as LuaTable; return((luaTable != null) ? new Lua.Result(luaTable.GetValue(StringToTableIndex(variable))) : Lua.NoResult); //--- Was (unoptimized): //return SafeGetLuaResult(string.Format("return Variable[\"{0}\"]", new System.Object[] { StringToTableIndex(variable) })); }
private void execOrderFileWrite(String targetFile, Dictionary <String, Double> config, String originalOrderFile) { //check which format it is LuaTable tab = ReadConfigOrder(originalOrderFile); LuaTable orderTab = (LuaTable)tab.GetValue("order"); LuaTable dataTab = (LuaTable)tab.GetValue("data"); if (orderTab != null && dataTab != null) { //we have standard format this.execOrderFileWriteNewStyle(targetFile, config, tab); } else { this.execOrderFileWriteOldStyle(targetFile, config); } }
public static void Main(string[] cmd_args_1938475092347027340582734) // random name doesnt interfere with my variables { // Create a global environment LuaTable t = LuaRuntime.CreateGlobalEnviroment(); // to add an item, dont use AddValue, it sticks it into the back // instead, use SetNameValue t.SetNameValue("obj", new LuaString("sample object")); // we can set the MetaTable of item "obj", but first we must get it from // the global environment: LuaValue val = t.GetValue("obj"); // We can then print "val" Console.WriteLine(val.ToString()); // --> sample object // to register methods, use the Register function (using Addresses or delegates) t.Register("samplefunc", delegate(LuaValue[] args) { return(new LuaNumber(100)); }); // To run Lua, use the Run function in LuaRuntime // we pass "t" as the specified environment, otherwise it will // create a new environment to run in. LuaRuntime.Run("print(\"obj:\", obj, \"\nsamplefunc:\", samplefunc())", t); // we can also call .NET methods using Lua-created .NET object // such as: LuaRuntime.Run("obj2 = script.create(\"CSharpExampleProject.TestClass\")", t); LuaRuntime.Run("print(\"testint:\", obj2.testint, \"TestFunc:\", obj2.TestFunc())", t); // the reason for this is because script.create returns an advanced Userdata with // metatables that check any indexing or setting and map them to the .NET object // if it doesn't find it, it throws an error //LuaRuntime.Run("obj2.ThisValueDoesntExistInDotNet = \"hey\"", t); // the same value was printed twice, with different functions each time, proving its not actually there: //Console.WriteLine(LuaRuntime.Run("return \"Sample attemption at creating an object: \" .. tostring(obj2.ThisValueDoesntExistInDotNet)", t)); // Console.WriteLine was used to show that you can print the returned value of executed code //LuaRuntime.Run("print(obj2.ThisValueDoesntExistInDotNet)", t); // Lua can also create "classes" LuaRuntime.Run("c = class()", t); Console.WriteLine(LuaRuntime.Run("return c", t)); // You can also call functions defined in #Lua LuaFunction f = LuaRuntime.Run("return function() print\"a function says hai\" end", t) as LuaFunction; f.Invoke(new LuaValue[] { }); // Let you see the output Console.Write("Press any key to continue . . . "); Console.ReadKey(true); }
/// <summary> /// Sets the value of a field in a Lua table element. /// </summary> /// <param name="table">Table name.</param> /// <param name="element">Name of an element in the table.</param> /// <param name="field">Name of a field in the element.</param> /// <param name="value">The value to set the field to.</param> public static void SetTableField(string table, string element, string field, object value) { Lua.WasInvoked = true; LuaTable luaTable = Lua.Environment.GetValue(table) as LuaTable; if (luaTable == null) { throw new System.NullReferenceException("Table not found in Lua environment: " + table); } LuaTable elementTable = luaTable.GetValue(StringToTableIndex(element)) as LuaTable; if (elementTable == null) { Lua.Run(string.Format("{0}[\"{1}\"] = {{}}", table, StringToTableIndex(element))); elementTable = luaTable.GetValue(StringToTableIndex(element)) as LuaTable; if (elementTable == null) { throw new System.NullReferenceException("Unable to find or add element: " + element); } } elementTable.SetNameValue(StringToTableIndex(field), LuaInterpreterExtensions.ObjectToLuaValue(value)); //--- Was (unoptimized): //if (DoesTableElementExist(table, element)) { // bool isString = (value != null) && (value.GetType() == typeof(string)); // string valueInLua = isString // ? DoubleQuotesToSingle((string) value) // : ((value != null) ? value.ToString().ToLower() : "nil"); // Lua.Run(string.Format("{0}[\"{1}\"].{2} = {3}{4}{3}", // new System.Object[] { table, // StringToTableIndex(element), // StringToTableIndex(field), // (isString ? "\"" : string.Empty), // valueInLua }), // DialogueDebug.LogInfo); //} else { // if (DialogueDebug.LogWarnings) { // Debug.LogWarning(string.Format("{0}: Entry \"{1}\" doesn't exist in table {2}[]; can't set {3} to {4}", // new System.Object[] { DialogueDebug.Prefix, StringToTableIndex(element), table, field, value })); // } //} }
public static LuaValue Require(LuaValue[] args) { // get loaders table LuaTable t = (LuaRuntime.GlobalEnvironment.GetValue("package") as LuaTable).GetValue("loaders") as LuaTable; if (t == null) { throw new Exception("Cannot get loaders table from package module!"); } if (t.Count == 0) { throw new Exception("Loaders table is empty!"); } // whether package was found/loaded LuaBoolean b = LuaBoolean.False; LuaValue module = null; foreach (LuaValue key in t.Keys) { LuaFunction f = t.GetValue(key) as LuaFunction; if (f != null) { LuaMultiValue lmv = f.Invoke(new LuaValue[] { new LuaString(args[0].Value.ToString()) }) as LuaMultiValue; b = lmv.Values[0] as LuaBoolean; if (b.BoolValue == true) { module = lmv.Values[1]; break; } } else { throw new Exception("Cannot cast type '" + t.GetValue(key).GetType().ToString() + "' to type 'LuaFunction'"); } } if (b.BoolValue == false) { Console.WriteLine("Could not load package '" + args[0].Value.ToString() + "'!"); } return(module); }
public static Varargs IPairs(LuaTable t) { var length = t.Length(); Func <double, object> func = index => { index++; return(index > length ? null : new Varargs(index, t.GetValue(index))); }; return(new Varargs(func, t, 0.0)); }
protected Record ReadRecord(LuaTable table, TBean type) { string tagName = table.GetValue(TAG_KEY)?.ToString(); if (DataUtil.IsIgnoreTag(tagName)) { return(null); } var data = (DBean)type.Apply(LuaDataCreator.Ins, table, (DefAssembly)type.Bean.AssemblyBase); var tags = DataUtil.ParseTags(tagName); return(new Record(data, RawUrl, tags)); }
public LuaTValue GetLuaObject(string luaAccessorCode) { LuaTable curTable = Globals; string[] split = luaAccessorCode.Split('.'); for (int i = 0; i < split.Length - 1; i++) { if (curTable == null) { return(null); } LuaTValue val = curTable.GetValue(split[i]); if (val == null || val.Type != LuaType.Table) { return(null); } curTable = val.Table; } return(curTable.GetValue(split.Last())); }
/// <summary> /// Gets the value with the specified string key. Returns a standard type such as /// <c>string</c>, <c>float</c>, <c>bool</c>, or <c>null</c>. If the value /// is a table, it returns a LuaTableWrapper around it. /// </summary> /// <param name="key">Key.</param> public object this [string key] { get { if (luaTable == null) { if (DialogueDebug.LogErrors) { Debug.LogError(string.Format("{0}: Lua table is null; lookup[{1}] failed", new object[] { DialogueDebug.Prefix, key })); } return(null); } LuaValue luaValue = LuaNil.Nil; if (luaTable.Length > 0) { // Get list value: luaValue = luaTable.GetValue(Tools.StringToInt(key)); } else { // Get dictionary value: LuaValue luaValueKey = luaTable.GetKey(key); if (luaValueKey == LuaNil.Nil) { //--- Suppressed: if (DialogueDebug.LogErrors) Debug.LogError(string.Format("{0}: Lua table does not contain key [{1}]", new string[] { DialogueDebug.Prefix, key })); return(null); } luaValue = luaTable.GetValue(key); } if (luaValue is LuaTable) { return(new LuaTableWrapper(luaValue as LuaTable)); } else { return(LuaInterpreterExtensions.LuaValueToObject(luaValue)); } } }
/// <summary> /// Chat Mapper function. See the online Chat Mapper manual for more details: http://www.chatmapper.com /// </summary> private static string GetStatusKey(LuaTable asset1, LuaTable asset2) { if ((asset1 == null) || (asset2 == null)) { if (DialogueDebug.LogWarnings) { Debug.LogWarning(DialogueDebug.Prefix + ": Syntax error in status function"); } return("INVALID"); } string asset1Name = StringToTableIndex(asset1.GetValue("Name").ToString()); string asset2Name = StringToTableIndex(asset2.GetValue("Name").ToString()); return(asset1Name + ',' + asset2Name); }
public static LuaValue remove(LuaValue[] values) { LuaTable table = values[0] as LuaTable; int index = table.Length; if (values.Length == 2) { LuaNumber number = values[1] as LuaNumber; index = (int)number.Number; } LuaValue item = table.GetValue(index); table.RemoveAt(index); return(item); }
/// <summary> /// Chat Mapper function. See the online Chat Mapper manual for more details: http://www.chatmapper.com /// </summary> private static string GetRelationshipKey(LuaTable actor1, LuaTable actor2, string relationshipType) { if ((actor1 == null) || (actor2 == null) || (relationshipType == null)) { if (DialogueDebug.LogWarnings) { Debug.LogWarning(DialogueDebug.Prefix + ": Syntax error in relationship function"); } return("INVALID"); } string actor1Name = StringToTableIndex(actor1.GetValue("Name").ToString()); string actor2Name = StringToTableIndex(actor2.GetValue("Name").ToString()); string relationshipString = SanitizeForStatusTable(relationshipType.ToString()); return(string.Format("{0},{1},'{2}'", new System.Object[] { actor1Name, actor2Name, relationshipString })); }
public static LuaValue UnPack(LuaValue[] values) { LuaTable table = values[0] as LuaTable; LuaNumber startNumber = values.Length > 1 ? values[1] as LuaNumber : null; LuaNumber lengthNumber = values.Length > 2 ? values[2] as LuaNumber : null; int start = startNumber == null ? 1 : (int)startNumber.Number; int length = lengthNumber == null ? values.Length : (int)lengthNumber.Number; LuaValue[] section = new LuaValue[length]; for (int i = 0; i < length; i++) { section[i] = table.GetValue(start + i); } return(new LuaMultiValue(section)); }
private static void PrintTable(LuaTable tbl, string indent, LuaValue _key = null) { /* sample output: * table: 002CCBA8 * { * field = value * X = 10 * y = function: 002CCBA8 * } */ string i = indent; A8Console.Write(i); if (_key != null) { A8Console.Write(_key.ToString() + " = "); } A8Console.WriteLine(tbl.ToString() + "\n" + i + "{"); foreach (LuaValue key in tbl.Keys) { LuaValue v = tbl.GetValue(key); if (v.GetTypeCode() == "table") { // check that its not a reference of itself if (!scanned.ContainsKey(key)) { scanned.SetKeyValue(key, v); PrintTable(v as LuaTable, i + " ", key); } else { A8Console.WriteLine(i + " " + key.ToString() + " = " + v.ToString()); } } else { scanned.SetKeyValue(key, v); A8Console.WriteLine(i + " " + key.ToString() + " = " + v.ToString()); } }/* * foreach (LuaValue key in tbl.MetaTable.Keys) * { * A8Console.WriteLine(i + "(MetaTable): " + key.ToString() + " = " + tbl.MetaTable.GetValue(key).ToString()); * }*/ A8Console.WriteLine(i + "}"); }
public static LuaValue Next(LuaValue[] values) { LuaTable table = values[0] as LuaTable; LuaValue index = values.Length > 1 ? values[1] : LuaNil.Nil; LuaValue prevKey = LuaNil.Nil; LuaValue nextIndex = LuaNil.Nil; foreach (var key in table.Keys) { if (prevKey.Equals(index)) { nextIndex = key; break; } prevKey = key; } return(new LuaMultiValue(new LuaValue[] { nextIndex, table.GetValue(nextIndex) })); }
private void execOrderFileWriteNewStyle(String targetFile, Dictionary <String, Double> config, LuaTable tableData) { String tableStr = "{"; tableStr += Environment.NewLine; tableStr += "data = "; tableStr += (tableData.GetValue("data") as LuaTable).MyToString(); tableStr += ","; tableStr += Environment.NewLine; tableStr += "order = "; tableStr += generateOrderTable(config); tableStr += Environment.NewLine; tableStr += "}"; this.saveOrderData(targetFile, tableStr); }
public static Varargs Unpack(LuaTable list, object i = null, object j = null) { var listLength = list.Length(); var startIndex = ConvertToNumber(i, 2, 1.0); var length = ConvertToNumber(j, 3, listLength); if (startIndex < 1) { return(Varargs.Empty); } length = Math.Min(length, listLength - startIndex + 1); var array = new object[(int)length]; var arrayIndex = 0; for (var k = startIndex; k < startIndex + length; k++) { array[arrayIndex++] = list.GetValue(k); } return(new Varargs(array)); }
private static void SetPropertyValue(object obj, object value, PropertyInfo propertyInfo) { if (propertyInfo.PropertyType.FullName == "System.Int32") { propertyInfo.SetValue(obj, (int)(double)value, null); } else if (propertyInfo.PropertyType.IsEnum) { object enumValue = Enum.Parse(propertyInfo.PropertyType, (string)value); propertyInfo.SetValue(obj, enumValue, null); } else if (propertyInfo.PropertyType.FullName == "System.Drawing.Image") { LuaTable enviroment = currentModule.GetValue("_G") as LuaTable; LuaString workDir = enviroment.GetValue("_WORKDIR") as LuaString; var image = System.Drawing.Image.FromFile(Path.Combine(workDir.Text, (string)value)); propertyInfo.SetValue(obj, image, null); } else { propertyInfo.SetValue(obj, value, null); } }
public static LuaValue IPairs(LuaValue[] values) { LuaTable table = values[0] as LuaTable; LuaFunction func = new LuaFunction( (LuaValue[] args) => { LuaTable tbl = args[0] as LuaTable; int index = (int)(args[1] as LuaNumber).Number; int nextIndex = index + 1; if (nextIndex <= tbl.Count) { return(new LuaMultiValue(new LuaValue[] { new LuaNumber(nextIndex), tbl.GetValue(nextIndex) })); } else { return(LuaNil.Nil); } } ); return(new LuaMultiValue(new LuaValue[] { func, table, new LuaNumber(0) })); }
private static object LuaRawGet(LuaTable t, object index) { return(t.GetValue(index, true)); } // func LuaRawGet
protected override object OnIndex(object key) => base.OnIndex(key) ?? f.GetValue(key);
} // proc GetStackFrame protected override object OnIndex(object key) => base.OnIndex(key) ?? parentFrame?.GetValue(key);
private static object LuaRawGet(LuaTable t, object index) => t.GetValue(index, true);
private static object LuaRawGet(LuaTable t, object index) { return t.GetValue(index, true); } // func LuaRawGet