背景

  在很多时候我们代码中的一些逻辑操作并不能够硬编码到代码中,我们可能希望通过配置来完成这个操作,所以这个时候我们就需要有一些脚本语言能够处理这些操作,在c#语言中比较常见的就是通过引入nlua这个动态库来引入lua脚本语言从而达到灵活配置的目的,这篇文章主要是通过具体的实例来说明在c#中如何通过引入nlua并调用配置的脚本。

步骤

1 引入nlua.dll

  这个dll是一个很轻量级的库,100kb左右,引用这个库可以通过nuget包管理器来引用,当前引用的版本是1.5.7.0,我们看看引用之后的添加了哪些dll。

这个里面lua54.dll有x86和x64两个类型的版本,这个在使用的时候需要注意因为我们生成设置选择的是any cpu所以这里会有两个版本的dll,这里使用的时候需要注意。

2 具体用法

  下面通过一个控制台应用程序来看看这个脚本到底该怎么使用,这里包括直接创建表达式,注册方法并使用lua调用c#函数以及直接导入c#的库然后再调用里面内部的方法这三个方面进行描述。

  2.1 直接创建表达式

       我们来直接看控制台程序中的代码

class program
 {
  static void main(string[] args)
  {
   using (var state = new lua())
   {
    //evaluating simple expressions:
    //lua can return multiple values, for this reason dostring return a array of objects
    var res0 = state.dostring("return 10 + 3*(5 + 2)")[0];
    console.writeline($"output result0:{res0}");

    //passing raw values to the state:
    double val = 12.0;
    state["x"] = val; // create a global value 'x' 
    var res1 = (double)state.dostring("return 10 + x*(5 + 2)")[0];
    console.writeline($"output result1:{res1}");

    //retrieving global values:
    state.dostring("y = 10 + x*(5 + 2)");
    double y = (double)state["y"]; // retrieve the value of y
    console.writeline($"y result:{y}");    
    
    console.readkey();
   }
  }}

注意事项:

  首先来看这个注释:lua can return multiple values, for this reason dostring return a array of objects,就是直接调用dostring方法的时候返回的结果是一个object[]类型,所以这里需要取结果的时候要取用第一个 

  2.2 注册lua function

  这里我们通过直接在dostring中定义好function,然后通过call方法进行调用,我们再来看下面的示例及返回结果

class program
 {
  static void main(string[] args)
  {
   using (var state = new lua())
   {
    //retrieving lua functions:
    state.dostring(@"function scriptfunc (val1, val2)
           if val1 > val2 then
            return val1 + 1
           else
            return val2 - 1
           end
          end
          ");
    var scriptfunc = state["scriptfunc"] as luafunction;
    var funcres = scriptfunc.call(3, 5).first();
    console.writeline($"func result:{funcres}");

    console.readkey();
   }
  }
}

  同样的我们也来看看最终执行的结果

  2.3 lua调用c#函数

  下面的例子包含了几种不同的参数类型及返回类型用来演示调用的完整过程。

using system;
using system.linq;
using nlua;

namespace nluaconsoleapp
{
 class program
 {
  static void main(string[] args)
  {
   using (var state = new lua())
   {
    ////---------------------------------------------------lua调用c#函数
    testclass obj = new testclass();

    // 注册clr对象方法到lua,供lua调用 typeof(testclass).getmethod("testprint")
    state.registerfunction("testprint", obj, obj.gettype().getmethod("testprint"));

    // 注册clr对象方法到lua,供lua调用 typeof(testclass).getmethod("anotherfunc")
    state.registerfunction("anotherfunc", obj, obj.gettype().getmethod("anotherfunc"));

    // 注册clr静态方法到lua,供lua调用
    state.registerfunction("teststaticprint", null, typeof(testclass).getmethod("teststaticprint"));

    state.dostring("testprint(10,20)");
    state.dostring("anotherfunc('10','20')");
    state.dostring("teststaticprint()");

    console.readkey();
   }
  }

  class testclass
  {

   public int testprint(int num,int num2)
   {
    var result = num + num2;
    console.writeline("print result:" + result);
    return result;
   }

   public void anotherfunc(string val1, string val2)
   {
    console.writeline($"mytest,param1:{val1},param2:{val2}");
   }

   public static void teststaticprint()
   {
    console.writeline("teststaticprint");
   }
  }

 }
}

  同样的我们来看整个测试的返回完整结果。

  2.4 通过import导入命名空间引用c#函数

  这个是按照进行模拟的,但是在调用的时候总是报错,现贴出具体的示例供后面排查使用

class program
 {
  static void main(string[] args)
  {
   using (var state = new lua())
   {
    state.loadclrpackage();
    state.dostring(@" import ('system.web') ");
    state.dostring(@" client = webclient() ");
    state.dostring(@"local res = client:downloadstring('http://nlua.org')");

    console.readkey();
   }
  }
 }

  这个就是说通过调用c#程序集并引入命名空间,然后调用其内部的webclient方法,这个在调试的时候一直都是报错,这个暂时记录供以后进行排查错误

3 总结

  这里有一些地方需要注意lua对象是实现了idispose接口的,所以我们在使用的时候需要注意使用using方式或者是使用后调用dispose方法来对资源进行释放。另外c#中引入lua脚本的常见主要是适用于部分调用过程不适合硬编码在代码里而适合放在配置中,通过配置不同的lua脚本从而对程序进行定制化操作,是对现有代码一个很好的补充,另外对于调用c#中dll的方法出现的问题还在研究中,后面发现了再更新此过程。

以上就是如何在c#中集成lua脚本的详细内容,更多关于c#中集成lua脚本的资料请关注www.887551.com其它相关文章!