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添加以下内容:
- <?xml version="1.0" encoding="utf-8" ?>
- <configuration>
- <startup useLegacyV2RuntimeActivationPolicy="true">
- <supportedRuntime version="v4.0" sku = ".NETFramework,Version=v4.0"/>
- <supportedRuntime version="v2.0.50727"/>
- </startup>
- </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代码:
- using LuaInterface;
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
-
- namespace lua_test
- {
- class MyClass {
- public string MyStr(string s)
- {
- return s + " World !";
- }
- }
- class Program
- {
- public static Lua m_lua = null;
- static public void init() {
- MyClass my = new MyClass();
-
- m_lua.RegisterFunction("MyStr", my, my.GetType().GetMethod("MyStr"));
- m_lua.DoFile("lua_test.lua");
- }
- static void Main(string[] args)
- {
- m_lua = new Lua();
- init();
-
- Object[] objs = m_lua.GetFunction("MyNum").Call(100);
-
- foreach(Object obj in objs){
- Console.WriteLine(obj);
- }
- Console.ReadLine();
- }
- }
- }
Demo下载:
http://download.csdn.Net/detail/e421083458/8432515
PS:最简单的学习方法就是拿到一个可以运行的Demo。
相关文档:
http://www.cnblogs.com/zwywilliam/p/5999924.html