正文

Lua编程示例(二):面向对象、metatable对表进行扩展(lua面向对象是怎么实现的)学到了

文章摘要

这篇文章展示了在Lua语言中使用自定义计数器类和metatable的技巧。文章通过定义一个带有`get`和`inc`方法的`counter`类,并创建了两个实例`counter`和`counter2`,展示了如何实现计数功能。`counter2`继承了`counter`的属性,并定义了自定义的行为。文章还探讨了metatable的使用,定义了一个表`mt`并将其作为metatable应用于`tb1`,实现了表的自定义方法。此外,文章详细展示了如何在metatable中实现表的加法操作、索引检查和值设置,包括定义`__add`、`__index`和`__newindex`方法。最后,文章通过测试展示了这些方法的实际使用效果,包括`tb1`的元素赋值和属性拦截功能。

 counter={ count=0 } function counter.get(self) return self.count end function counter:inc() self.count=self.count+1 end print(counter.get(counter)) counter.inc(counter) print(counter.get(counter)) counter2={ count=4, get=counter.get, inc=counter.inc, } print(counter2:get()) counter.inc(counter2) print(counter2.get(counter2)) print() tb1={ “alpha”,”beta”,”gamma”} mt={} setmetatable(tb1,mt) print(getmetatable(tb1)==mt) print() function mt.__add(a,b) local result=setmetatable({},mt) for i=1,#a do table.insert(result,a[i]) end for i=1,#b do table.insert(result,b[i]) end return result end tb2= ” return result end print(tb1) function mt.__index(tb1,key) print(“there is no “..key..” in the table”) return nil end print(tb1[“fsy”]) function mt.__newindex(a,key,v) if( key==”haha”) then error(” Stop laugh!”,2) else rawset(a,key,v) end end tb1.haha=”heihei”