Luainterface,如何从c#代码中传递整个类?

时间:2012-09-02 19:51:43

标签: c# compiler-construction lua luainterface

我想将整个类从c#代码传递给lua,所以我可以在LUA中创建一个新对象并使用它的方法,字段等。当它完成后,我想知道是否可以在lua中使用对象,这些对象是用c#代码创建的,然后以某种方式传递给lua。

这是我的代码: atm,它不可能在类Person1的luainterface对象中创建然后使用它的函数 当我输入say()到lua脚本编写器(没有在那里创建任何对象)时,我得到Person2.say()的输出

using System;
using LuaInterface;
using System.Reflection;

namespace ConsoleApplication
{


public class Person1
{
    public void say()
    {
        Console.WriteLine("person1 says: hehe");
    }
}


public class Person2
{
    public void say()
    {
        Console.WriteLine("person2 says: hihi");
    }
}

class Class1
{
    static void Main(string[] args)
    {
        Lua lua_compiler = new Lua();

        Person1 person1 = new Person1();
        Person2 person2 = new Person2();

        lua_compiler.RegisterFunction("say", person1, person1.GetType().GetMethod("say"));
        lua_compiler.RegisterFunction("say", person2, person2.GetType().GetMethod("say"));


        while (true)
        {
            string line = Console.ReadLine();
            try { lua_compiler.DoString(line); }
            catch { }
        }
    }
}
}

1 个答案:

答案 0 :(得分:2)

    Person1 person1 = new Person1();
    Person2 person2 = new Person2();

    lua_compiler["person1"] = person1;
    lua_compiler["person2"] = person2;


    while (true)
    {
        string line = Console.ReadLine();
        try { lua_compiler.DoString(line); }
        catch { }
    }

在该行中你可以使用person1:say()或person2:say()

如果你的班级有很多功能和属性,那么传递全班是很费时的。