Skip to content

Strange Metamethod Behavior #236

@paulevsGitch

Description

@paulevsGitch

LuaCSharp version: 0.5.0

During testing metamethods I found some weird behavior. If metamethod (for example adding) is defined inside C# object then it has a huge chance to fail in the Lua (sometimes method is not called at all). If it is assigning to a new local then method is not called and local became nil, if it is assigning to one of created object then result is successful.

Here is an example C# class:

[LuaObject]
public partial class LuaTestObj {
	private float x;
	private float y;

	[LuaMember("x")]
	public float X {
		get => x;
		set => x = value;
	}

	[LuaMember("y")]
	public float Y {
		get => y;
		set => y = value;
	}

	[LuaMember("create")]
	public static LuaTestObj Create(float x, float y) {
		return new LuaTestObj() {
			x = x,
			y = y
		};
	}

	[LuaMetamethod(LuaObjectMetamethod.Add)]
	public static LuaTestObj Add(LuaTestObj a, LuaTestObj b) {
		return new LuaTestObj() {
			x = a.x + b.x,
			y = a.y + b.y
		};
	}

	[LuaMetamethod(LuaObjectMetamethod.ToString)]
	public override string ToString() {
		return $"({x}, {y})";
	}
}

And an example of Lua code with output:

local a = TestObj.create(1, 2)
local b = TestObj.create(3, 4)

print("a ->", tostring(a)) -- prints (1, 2)
print("b ->", tostring(b)) -- prints (3, 4)
print()

local c = a + b

print("c ->", tostring(c)) -- prints nil, __add is not called
print("a + b ->", tostring(a + b)) -- prints nil, __add is not called
print()

a = a + b
print("a ->", tostring(a)) -- prints (4, 6), __add is called
Image

However if the same object is defined on Lua side:

TestObj = {
	mt = {
		__add = function (a, b)
			return TestObj.create(a.x + b.x, a.y + b.y)
		end,
		__tostring = function (a)
			return "(" .. a.x .. ", " .. a.y .. ")"
		end
	},
	create = function (x, y)
		local obj = {
			x = x,-- | 0.0,
			y = y -- | 0.0
		}
		setmetatable(obj, TestObj.mt)
		return obj
	end
}

The results are always correct:

Image

I'm not sure if this is a bug or I'm doing something incorrectly.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions