.net core中載入lua指令碼的類庫- MoonSharp
阿新 • • 發佈:2019-02-15
前言
MoonSharp是一個支援C#呼叫lua指令碼的類庫,支援.net, .net core, mono, unity,因此在.net core中也能夠使用,而且載入和呼叫lua也很方便簡單;
官網:http://www.moonsharp.org/
原始碼:https://github.com/xanathar/moonsharp
nuget:PM> Install-Package MoonSharp
使用
載入指令碼
1 string scriptCode = @" 2 sum = 0 3 for i = 1, 100 do4 sum = sum + i 5 end 6 return sum"; 7 DynValue res = Script.RunString(scriptCode); //執行指令碼 8 Console.WriteLine(res.Number); //輸出:5050
載入指令碼檔案:
Console.WriteLine(Script.RunFile("luatest.txt").Number); //指定檔名載入指令碼並執行
檔案內容:
sum = 0View Codefor i = 1, 100 do sum = sum + i end return sum
傳遞資料(lua全域性變數)
1 string scriptCode = @" 2 function fact (n) 3 if (n == 0) then 4 return 1 5 else 6 return n*fact(n - 1)7 end 8 end 9 return fact(num)"; 10 11 Script script = new Script(); 12 script.Globals["num"] = 5; //對指令碼中的全域性變數 num 賦值 13 14 Console.WriteLine(script.DoString(scriptCode).Number); //輸出:120
lua函式的定義與呼叫
1 Script script = new Script(); 2 //先載入定義的函式 3 script.DoString(@" 4 function fact(n) 5 if (n == 0) then 6 return 1 7 else 8 return n * fact(n - 1) 9 end 10 end 11 "); 12 13 //如果該函式會重複利用的,那麼就應該這麼呼叫,而不是每次都呼叫DoString載入指令碼呼叫(每次都載入指令碼是費效能的) 14 Console.WriteLine(script.Call(script.Globals["fact"], 5).Number); //輸出:120 15 Console.WriteLine(script.Call(script.Globals["fact"], DynValue.NewNumber(5)).Number); //和上面的一樣
傳遞集合引數
1 Script script = new Script(); 2 script.DoString(@" 3 function sum(list) 4 local total = 0; 5 for i,v in ipairs(list) do 6 total = total + v; 7 end 8 return total; 9 end 10 "); 11 12 Console.WriteLine(script.Call(script.Globals["sum"], new List<int>() { 1, 3, 5, 7, 9 })); //輸出:25
多值返回:Tuple
1 Script script = new Script(); 2 script.DoString(@" 3 function sum(kv) 4 local total = 0; 5 local ks = ''; 6 for k,v in pairs(kv) do 7 total = total + v; 8 ks = ks .. k .. ','; --字串拼接 9 end 10 return ks, total; --多值返回:Tuple 11 end 12 "); 13 14 var dict = new Dictionary<string, int>() //傳遞字典 15 { 16 { "k1", 1 }, 17 { "k2", 2 }, 18 { "k3", 3 }, 19 }; 20 var tp = script.Call(script.Globals["sum"], dict).Tuple; //返回tuple型別 21 Console.WriteLine(tp[0].String); //輸出:k1,k2,k3, 22 Console.WriteLine(tp[0].Number); //輸出:0, 如果是String型別的呼叫Number會輸出:0 23 Console.WriteLine(tp[1].Number); //輸出:6
lua指令碼中載入和呼叫C#程式碼定義的函式
1 public static void CallList() 2 { 3 Script script = new Script(); 4 script.Globals["getlist"] = (Func<List<int>, List<int>>)GetList; //載入C#中定義的函式 5 script.DoString(@" 6 function sum(list) 7 local total = 0; 8 for i,v in ipairs(list) do 9 total = total + v; 10 end 11 return total; 12 end 13 "); 14 15 string scode = @"return sum(getlist( { 11, 12, 13, 14, 15 } ))"; //指令碼中呼叫C#中定義的函式 16 Console.WriteLine(script.DoString(scode)); //輸出:120 17 18 } 19 20 private static List<int> GetList(List<int> list) 21 { 22 for (int i = 1; i <= 10; i++) 23 list.Add(i); 24 return list; 25 }