【问题标题】:Luainterface, how to pass a whole class from a c# code?Luainterface,如何从 c# 代码传递整个类?
【发布时间】:2012-10-23 23:01:31
【问题描述】:

我想将整个类从 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 { }
        }
    }
}
}

【问题讨论】:

    标签: c# compiler-construction lua luainterface


    【解决方案1】:
        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()

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-23
      • 2017-10-31
      相关资源
      最近更新 更多