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

随心笔谈2年前发布 admin
205 0 0

文章摘要

这篇文章介绍了在C语言中使用跨编译器编写代码的示例,重点讲述了如何定义和使用自定义表(tables)及其方法。文章首先定义了`counter`表,包括`count`计数器、`get`获取计数值的方法和`inc`增加计数的方法。通过调用`get`和`inc`函数,展示了如何实现简单的计数功能。 文章进一步定义了`counter2`表,并将其`count`属性初始化为4,同时复制了`counter`表的`get`和`inc`方法。通过打印和调用这些方法,展示了表间的数据传递和方法引用的使用。 接下来,文章探讨了如何使用`metatable`将标准表应用于自定义表。通过定义`tb1`为一个字符串表,并将其映射到空表`mt`,验证了`metatable`的使用方法,同时通过自定义方法`__index`和`__newindex`实现了动态索引操作。 文章还展示了如何通过自定义表的方法实现动态索引功能,并通过错误处理机制`__newindex`实现了对特定键的特殊处理。最后,文章总结了通过这些操作实现的自定义表功能及其在C语言跨编译中的应用。


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”

© 版权声明

相关文章