.net core中加载lua脚本的类库: MoonSharp

前言

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

使用

加载脚本

             string scriptCode = @"
sum = 0
for i = 1, 100 do
sum = sum + i
end
return sum";
DynValue res = Script.RunString(scriptCode); //运行脚本
Console.WriteLine(res.Number); //输出:5050

加载脚本文件:

Console.WriteLine(Script.RunFile("luatest.txt").Number);   //指定文件名加载脚本并运行

文件内容:

sum =
for i = , do
sum = sum + i
end
return sum

传递数据(lua全局变量)

             string scriptCode = @"
function fact (n)
if (n == 0) then
return 1
else
return n*fact(n - 1)
end
end
return fact(num)"; Script script = new Script();
script.Globals["num"] = ; //对脚本中的全局变量 num 赋值 Console.WriteLine(script.DoString(scriptCode).Number); //输出:120

lua函数的定义与调用

             Script script = new Script();
//先加载定义的函数
script.DoString(@"
function fact(n)
if (n == 0) then
return 1
else
return n * fact(n - 1)
end
end
"); //如果该函数会重复利用的,那么就应该这么调用,而不是每次都调用DoString加载脚本调用(每次都加载脚本是费性能的)
Console.WriteLine(script.Call(script.Globals["fact"], ).Number); //输出:120
Console.WriteLine(script.Call(script.Globals["fact"], DynValue.NewNumber()).Number); //和上面的一样
传递集合参数
             Script script = new Script();
script.DoString(@"
function sum(list)
local total = 0;
for i,v in ipairs(list) do
total = total + v;
end
return total;
end
"); Console.WriteLine(script.Call(script.Globals["sum"], new List<int>() { , , , , })); //输出:25
多值返回:Tuple
             Script script = new Script();
script.DoString(@"
function sum(kv)
local total = 0;
local ks = '';
for k,v in pairs(kv) do
total = total + v;
ks = ks .. k .. ','; --字符串拼接
end
return ks, total; --多值返回:Tuple
end
"); var dict = new Dictionary<string, int>() //传递字典
{
{ "k1", },
{ "k2", },
{ "k3", },
};
var tp = script.Call(script.Globals["sum"], dict).Tuple; //返回tuple类型
Console.WriteLine(tp[].String); //输出:k1,k2,k3,
Console.WriteLine(tp[].Number); //输出:0, 如果是String类型的调用Number会输出:0
Console.WriteLine(tp[].Number); //输出:6

lua脚本中加载和调用C#代码定义的函数

         public static void CallList()
{
Script script = new Script();
script.Globals["getlist"] = (Func<List<int>, List<int>>)GetList; //加载C#中定义的函数
script.DoString(@"
function sum(list)
local total = 0;
for i,v in ipairs(list) do
total = total + v;
end
return total;
end
"); string scode = @"return sum(getlist( { 11, 12, 13, 14, 15 } ))"; //脚本中调用C#中定义的函数
Console.WriteLine(script.DoString(scode)); //输出:120 } private static List<int> GetList(List<int> list)
{
for (int i = ; i <= ; i++)
list.Add(i);
return list;
}
上一篇:动态加载JS脚本


下一篇:探真无阻塞加载javascript脚本技术,我们会发现很多意想不到的秘密