Search code examples
c#lualuainterface

LuaInterface: Access objects properties


i'm using LuaInterface to register a getter for some objects i want to have available in Lua. E.G:

    public MyObject getObjAt(int index)
    {
        return _myObjects[index];
    }

my Lua file:

obj = getObjAt(3) 
print(obj.someProperty)    // Prints "someProperty"
print(obj.moooo)           // Prints "moooo"
print(obj:someMethod())    // Works fine, method is being executed

How exactly can i access the public object properties after returning them in Lua? Is that even possible or do i have to write getter for each object property?


Solution

  • You might find this code useful in understanding how to access the properties:

    class Lister
    {
        public string ListObjectMembers(Object o)
        {
            var result = new StringBuilder();
            ProxyType proxy = o as ProxyType;
    
            Type type = proxy != null ? proxy.UnderlyingSystemType : o.GetType();
    
            result.AppendLine("Type: " + type);
    
            result.AppendLine("Properties:");
            foreach (PropertyInfo propertyInfo in type.GetProperties())
                result.AppendLine("   " + propertyInfo.Name);
    
            result.AppendLine("Methods:");
            foreach (MethodInfo methodInfo in type.GetMethods())
                result.AppendLine("   " + methodInfo.Name);
    
    
            return result.ToString();
        }
    }
    

    and register the function:

    static Lister _lister = new Lister();
    private static void Main() {
        Interpreter = new Lua();
    
        Interpreter.RegisterFunction("dump", _lister,
        _lister.GetType().GetMethod("ListObjectMembers"));
    }
    

    Then in Lua:

    print(dump(getObjAt(3)))