您的位置:首页 > 编程语言 > Lua

KopiLua and LuaInterface

2014-04-03 10:09 766 查看
Lua的确是一个很有意思的语言,尤其是交互是如此的方便,在系统中潜入一个Lua也不会消耗多少资源,反而可以获得很大的灵活性.的确很有意思.

 

Lua在C#的移植使用的LuaInterface这个产品

在互联网上也有不少文章介绍如何在.net环境中使用Lua的,不过对于我们新手来说,可能有时候不是很容易看得清楚.

Lua相当于一个解释器,你在这个解释器中注册了一个函数,即可在一个外部文件中调用其中的函数

最简单而粗暴的写法

using System;
using System.Collections.Generic;
using System.Text;
using LuaInterface;

namespace ConsoleApplication1
{
class Program
{

static void Main(string[] args)
{
Program program = new Program();

Lua lua = new Lua();

//Register our C# functions
lua.RegisterFunction("DanSays", program, program.GetType().GetMethod("DanSays"));
lua.RegisterFunction("ThorSays", program, program.GetType().GetMethod("ThorSays"));
lua.RegisterFunction("TestFun", program, program.GetType().GetMethod("TestFun"));
lua.RegisterFunction("ReturnInt", program, program.GetType().GetMethod("ReturnInt"));

lua.DoString("DanSays('Hello'); ThorSays('Hi! Dan')");
lua.DoString("print('100asdf');");

lua.DoFile("scripts/Thursdays.lua");
Console.ReadLine();
Console.ReadLine();
Console.ReadLine();
}

public void DanSays(string s)
{
Console.WriteLine("Dan>" + s);
}

public void ThorSays(string s)
{
Console.WriteLine("Thor>" + s);
}

public void TestFun(Int32 aint)
{
Console.WriteLine("this is lua example, Number:" + aint.ToString());
}

public Int32 ReturnInt()
{
Console.WriteLine("Return Int");
return 110;
}
}
}


这种方式使用手工的方式注册函数名

值得主意的是,在lua的系统中”注册用的函数名”并不代表”对应的函数”就是一样的名称,两者是没有必然的联系的.

上面是参照 http://www.godpatterns.com/2006/05/scripting-with-lua-in-c.html 而弄出来的

 

然后有人就觉得不方便了 于是有了如下文章

http://blog.csdn.net/rcfalcon/article/details/5583095

 

实际上呢,

这是 www.gamedev.net/page/resources/_/reference/programming/sweet-snippets/using-lua-with-c-r2275

的简化版和弱化版

如果你按照 gamedev中的步骤做下去的话,会突然发现,编译错误.作为新手来说,肯定很头痛吧

 

21

这样子就不会有错误了

gamedev中的自动抽取类中有描述的函数,然后注册到lua解释器中,还能根据函数名来对对应的函数做出说明.

可以在一个帮助系统中使用这部分工作
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息