0

我想将整个类从 c# 代码传递给 lua,所以我可以在 LUA 中创建一个新对象并使用它的方法、字段等。完成后,我想知道是否可以在 lua 中使用对象,这些对象是在 ac# 代码中创建的,然后以某种方式传递给 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 { }
        }
    }
}
}
4

1 回答 1

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()

如果你的类有很多函数和属性,传递整个类是很耗时的。

于 2012-10-23T15:01:31.030 回答