neolithos / neolua

A Lua implementation for the Dynamic Language Runtime (DLR).
https://neolua.codeplex.com/
Apache License 2.0
471 stars 76 forks source link

How to use .NET object property in lua requiring .NET function #81

Closed Symbai closed 6 years ago

Symbai commented 6 years ago

NeoLua Version: 1.3.0

Example to reproduce:

struct MyStruct{

 bool _bla = true;
 public bool Bla => _bla;
 public bool Awesome => NamespaceXY.StaticClass.StaticFunction(this);

}

// .... in lua:
local abc = calledFunction() //returns a MyStruct
printf(abc.Bla) //works
printf(abc.Awesome) //empty / nil

Is there a way to get Awesome property accessible in lua?

neolithos commented 6 years ago

This and structs is a design error, this will slow down also the application. To many mem copies. Struct is in such a case the wrong declaration, it should be a class. As far I can see.

What is the content of StaticFunction?

Symbai commented 6 years ago

Can be anything such as:

static bool StaticFunction(MyStruct test)
{
    return NamespaceXY.AnotherClass.Aproperty && test.Bla;
}

This is just a basic example, in real these functions are much more complex. It also happens with classes. As long as a property needs to call a function in my application LUA cannot handle it.

neolithos commented 6 years ago

Btw. I can not compile your example because _bla

Error   CS0573  'Program.MyStruct': cannot have instance property or field initializers in structs  

I changed it to:

        static bool NegBla(MyStruct my)
            => !my.Bla;

        struct MyStruct
        {
            public bool Bla => true;
            public bool Awesome => NegBla(this);

        }
        static MyStruct getStruct()
            => new MyStruct();

        public static void Example()
        {
            using (var l = new Lua())
            {
                dynamic g = l.CreateEnvironment();
                g.t = new LuaTable();
                ((LuaTable)g.t).DefineFunction("getStruct", new Func<MyStruct>(getStruct));

                g.dochunk("local o = t.getStruct(); "+Environment.NewLine+
                    "print(o.Bla); print(o.Awesome); ", "test.lua");
            }
        }

Prints true and false.

But better would be:

    static bool NegBla(ref MyStruct my)
            => !my.Bla;

        struct MyStruct
        {
            public bool Bla => true;
            public bool Awesome => NegBla(ref this);

        }
Symbai commented 6 years ago

It works on my end too and all simple examples I tried to make for you work as well. I might have to figure out the reason it doesn't works on my more complex code myself then. Sorry for the trouble.