2

I am having problems changing members of a struct, which is a member of a class via the Lua interpreter MoonSharp.

My current test setup looks something like this:

class VectorClass
{
    public float X;
    public float Y;

    public Vector2(float X, float Y)
    {
        this.X = X;
        this.Y = Y;
    }
}

struct VectorStruct
{
    public float X;
    public float Y;

    public Vector2(float X, float Y)
    {
        this.X = X;
        this.Y = Y;
    }
}

For testing I have the vector object as a class and as a struct.

[MoonSharpUserData]
class MyClass
{
    public VectorClass VClass;
    public VectorStruct VStruct;
    
    public MyClass()
    {
        VClass = new VectorClass(0,0);
        VStruct = new VectorStruct(0, 0);
    }
}

This is the class which contains the struct/class.

class Program
{
    static void Main(string[] args)
    {
        Script script = new Script();
        MyClass classic = new MyClass();


        string scriptString = @"
                function changeVelocity()
                    MyClass.VStruct.X = 10
                    MyClass.VClass.X = 10
                end";

        UserData.RegisterAssembly();
        UserData.RegisterType<VectorClass>();
        UserData.RegisterType<VectorStruct>();

        script.Globals["MyClass"] = classic;
        script.DoString(scriptString);
        script.Call(script.Globals.Get("changeVelocity"));

        Console.WriteLine("Class: " + classic.VClass.X);
        Console.WriteLine("Struct: " + classic.VStruct.X);

        Console.ReadKey();
    }
}

In my main program I try to change the value of the struct and the class (only x) but it only works with the class.

I think there is some problem with the class being a Value-Type and not a Reference type. The API I'm working with uses a struct, which forces me to get the struct access to work but I can't even use a MoonSharp ProxyType.

Does anyone know a workaround without rewriting the code completely?

Jason Aller
  • 3,541
  • 28
  • 38
  • 38

1 Answers1

2

Yes, unlike classes structs store the value, not the reference, Moonsharp is not really good with that. A simple workaround could be making the Lua function create a new value, you can even bind that to a simple lambda function, like this:

string scriptString = @"
    function changeVelocity(MyClass)
        MyClass.VStruct = VStruct(10, MyClass.VStruct.Y)
        MyClass.VClass.X = 10
    end";

UserData.RegisterAssembly();
UserData.RegisterType<VectorClass>();
UserData.RegisterType<VectorStruct>();

script.Globals["VStruct"] = (Func<float, float, VectorStruct>)((x, y) => 
{ return new VectorStruct(x, y); });
script.DoString(scriptString);
script.Call(script.Globals.Get("changeVelocity"), classic);

check the last item in the glossary here for more info on the value-type thing: http://www.moonsharp.org/hardwire.html