c#调用脚本语言Lua——简单Demo

c#调用脚本语言Lua——简单Demo

配置:

Lua是一种很好的扩展性语言,Lua解释器被设计成一个很容易嵌入到宿主程序的库。LuaInterface则用于实现Lua和CLR的混合编程。
1. 下载c#下的Lua支持类库。下载地址:http://files.luaforge.NET/releases/luainterface/luainterface/2.0.3
将(lua51.dll\LuaInterface.dll)引用自己的项目中。
2. 修改App.config添加以下内容:

[html]  view plain  copy
 print ? 在CODE上查看代码片 派生到我的代码片
  1. <?xml version="1.0" encoding="utf-8" ?>  
  2. <configuration>  
  3.   <startup useLegacyV2RuntimeActivationPolicy="true">  
  4.     <supportedRuntime version="v4.0" sku = ".NETFramework,Version=v4.0"/>  
  5.     <supportedRuntime version="v2.0.50727"/>  
  6.   </startup>  
  7. </configuration>  



否则,运行代码会出现以下提示:
混合模式程序集是针对“v2.0.50727”版的运行时生成的,在没有配置其他信息的情况下,无法在 4.0 运行时中加载该程序集。

调用步骤:
1. 声明Lua虚拟机
    Lua m_lua = new Lua();
2. 将c#的对象方法注册到Lua中,使Lua可以调用该方法。
    class MyClass {
        public string MyStr(string s)
        {
            return s + " World !";
        }
    }
    MyClass my = new MyClass();
    m_lua.RegisterFunction("MyStr", my, my.GetType().GetMethod("MyStr"));
    
3. 加载Lua代码
    m_lua.DoFile("lua_test.lua"); 
    
4. 调用Lua方法
    Object[] objs = m_lua.GetFunction("MyNum").Call(100);

    
Demo代码:
[csharp]  view plain  copy
 print ? 在CODE上查看代码片 派生到我的代码片
  1. using LuaInterface;  
  2. using System;  
  3. using System.Collections.Generic;  
  4. using System.Linq;  
  5. using System.Text;  
  6. using System.Threading.Tasks;  
  7.   
  8. namespace lua_test  
  9. {  
  10.     class MyClass {  
  11.         public string MyStr(string s)  
  12.         {  
  13.             return s + " World !";  
  14.         }  
  15.     }  
  16.     class Program  
  17.     {  
  18.         public static Lua m_lua = null;        //创建lua虚拟机  
  19.         static public void init() {  
  20.             MyClass my = new MyClass();             //创建自定义类实例  
  21.             //在lua虚拟机(全局)中注册自定义函数,一边在lua文件中调用该函数  
  22.             m_lua.RegisterFunction("MyStr", my, my.GetType().GetMethod("MyStr"));  
  23.             m_lua.DoFile("lua_test.lua");           //加载lua文件(绝对路径)  
  24.         }  
  25.         static void Main(string[] args)  
  26.         {  
  27.             m_lua = new Lua();  
  28.             init();  
  29.             //加载乱文件后,使用GetFunction获取函数,再调用Call执行(传参数)  
  30.             Object[] objs = m_lua.GetFunction("MyNum").Call(100);  
  31.             //Call函数的返回值为一个Object数组  
  32.             foreach(Object obj in objs){  
  33.                 Console.WriteLine(obj);  
  34.             }  
  35.             Console.ReadLine();  
  36.         }  
  37.     }  
  38. }  

Demo下载:

http://download.csdn.Net/detail/e421083458/8432515


PS:最简单的学习方法就是拿到一个可以运行的Demo。

相关文档:

http://www.cnblogs.com/zwywilliam/p/5999924.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值