using System; using System.Collections.Generic; using System.Text; using LuaInterface; using System.Text.RegularExpressions; using System.Linq; namespace Aitex.UI.Charting.Model { public class LuaFunction { public static float[] CalcFunction(string function, List> dataList, string deviceName) { try { //对注释符号进行替换 function = function.Replace("//", "--"); //对变量进行替换 List fparams = new List(); foreach (var item in dataList) { var paraName = item.Key.Replace(".", "_"); fparams.Add(paraName); function = function.Replace(item.Key, paraName); } Lua lua = new Lua(); string functionTemplate = string.Format("LuaFunction = function ({1})\n\n{2} \nend", deviceName, string.Join(",", fparams.ToArray()), function); lua.DoString(functionTemplate); string baseFunction = TemplateFunction(dataList.Count); lua.DoString(baseFunction); // lua.DoFile("luaDemo_2.lua"); LuaInterface.LuaFunction luaFunc = lua.GetFunction("CombinatePrint"); object[] paras = dataList.Select((t) => { return t.Value; }).ToArray(); object[] objRet = luaFunc.Call(paras); double[] res = (objRet[0] as LuaTable).Values.Cast().ToArray(); //can not cast to float??!! float[] res1 = new float[res.Length]; for (int i = 0; i < res1.Length; i++) res1[i] = (float)res[i]; return res1; } catch (Exception) { return null; } } static string TemplateFunction(int paramCount) { StringBuilder sb = new StringBuilder(); sb.Append(" function CombinatePrint(...) "); sb.Append("local t = { } "); sb.Append("local n = arg.n; "); for (int i = 1; i <= paramCount; i++) { sb.AppendFormat("local e{0} = arg[{0}]:GetEnumerator() ", i); } sb.Append("local i=1 "); sb.Append("while e1:MoveNext() do "); for (int i = 2; i <= paramCount; i++) { sb.AppendFormat(" if e{0}:MoveNext() then ", i); } string paramstring = ""; for (int i = 1; i <= paramCount; i++) { if (paramstring != "") paramstring += ","; paramstring += string.Format("e{0}.Current", i); } sb.Append(" t[i]= LuaFunction(" + paramstring + ") "); sb.Append(" i = i+1 "); for (int i = 2; i <= paramCount; i++) { sb.Append(" end "); } sb.Append(" end "); sb.Append(" return t "); sb.Append(" end "); return sb.ToString(); } } }