记录一次xlua修复构造函数的经验

发布时间 2023-09-15 18:09:08作者: mc宇少

需求:类型A包含多个重载构造函数(包含参数数量相同但参数类型不同的情况)。

修复方法:像这种修构造函数的lua,会注入到所有符合条件的函数中(参数数量相同的),但可能你只需要修复其中一个,这个时候可以在lua函数内部进行类型判断,来决定时候走热更代码。

local A = function(self,jsonVehicleComponent,checkCollect)
	if jsonVehicleComponent:GetType() == typeof(CS.LitJson.JsonData) then
		--热更代码
		end
		self:A();
	end
end

本来修到这里就完事了,但修后面需求的时候发现了问题:在别的热更代码(lua)中调用了A的构造函数,报错了:

attempt to index local 'self' (a number value)

查出来是走到了上面修复的构造函数A中,由于传入的是lua的基本类型,导致jsonVehicleComponent:GetType()报了空指针,猜测是是C#的GetType()只能检查C#的类型,lua的基础类型调用GetType()会报这个错,后来改成了:

local A = function(self,jsonVehicleComponent,checkCollect)
	if type(jsonVehicleComponent) ~= "number" and jsonVehicleComponent:GetType() == typeof(CS.LitJson.JsonData) then
		--热更代码
		end
		self:A();
	end
end

加上了lua基础类型的判断就好了