LuaFunction.cs 3.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. using LuaInterface;
  5. using System.Text.RegularExpressions;
  6. using System.Linq;
  7. namespace Aitex.UI.Charting.Model
  8. {
  9. public class LuaFunction
  10. {
  11. public static float[] CalcFunction(string function, List<KeyValuePair<string, float[]>> dataList, string deviceName)
  12. {
  13. try
  14. {
  15. //对注释符号进行替换
  16. function = function.Replace("//", "--");
  17. //对变量进行替换
  18. List<string> fparams = new List<string>();
  19. foreach (var item in dataList)
  20. {
  21. var paraName = item.Key.Replace(".", "_");
  22. fparams.Add(paraName);
  23. function = function.Replace(item.Key, paraName);
  24. }
  25. Lua lua = new Lua();
  26. string functionTemplate = string.Format("LuaFunction = function ({1})\n\n{2} \nend", deviceName, string.Join(",", fparams.ToArray()), function);
  27. lua.DoString(functionTemplate);
  28. string baseFunction = TemplateFunction(dataList.Count);
  29. lua.DoString(baseFunction);
  30. // lua.DoFile("luaDemo_2.lua");
  31. LuaInterface.LuaFunction luaFunc = lua.GetFunction("CombinatePrint");
  32. object[] paras = dataList.Select((t) => { return t.Value; }).ToArray();
  33. object[] objRet = luaFunc.Call(paras);
  34. double[] res = (objRet[0] as LuaTable).Values.Cast<double>().ToArray(); //can not cast to float??!!
  35. float[] res1 = new float[res.Length];
  36. for (int i = 0; i < res1.Length; i++)
  37. res1[i] = (float)res[i];
  38. return res1;
  39. }
  40. catch (Exception)
  41. {
  42. return null;
  43. }
  44. }
  45. static string TemplateFunction(int paramCount)
  46. {
  47. StringBuilder sb = new StringBuilder();
  48. sb.Append(" function CombinatePrint(...) ");
  49. sb.Append("local t = { } ");
  50. sb.Append("local n = arg.n; ");
  51. for (int i = 1; i <= paramCount; i++)
  52. {
  53. sb.AppendFormat("local e{0} = arg[{0}]:GetEnumerator() ", i);
  54. }
  55. sb.Append("local i=1 ");
  56. sb.Append("while e1:MoveNext() do ");
  57. for (int i = 2; i <= paramCount; i++)
  58. {
  59. sb.AppendFormat(" if e{0}:MoveNext() then ", i);
  60. }
  61. string paramstring = "";
  62. for (int i = 1; i <= paramCount; i++)
  63. {
  64. if (paramstring != "") paramstring += ",";
  65. paramstring += string.Format("e{0}.Current", i);
  66. }
  67. sb.Append(" t[i]= LuaFunction(" + paramstring + ") ");
  68. sb.Append(" i = i+1 ");
  69. for (int i = 2; i <= paramCount; i++)
  70. {
  71. sb.Append(" end ");
  72. }
  73. sb.Append(" end ");
  74. sb.Append(" return t ");
  75. sb.Append(" end ");
  76. return sb.ToString();
  77. }
  78. }
  79. }