Lua编程示例(二):面向对象、metatable对表进行扩展
作者:暮色微凉
时间:2026-06-29
浏览:1
通过表和方法模拟类与对象,利用元表(metatable)扩展表功能,定义__add、__unm、__tostring、__index、__newindex等元方法,实现加法、取反、字符串转换、索引访问及赋值限制,展示了Lua元表在面向对象编程中的灵活应用,如运算符重载与属性保护。
本文目录
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={"aaa","bbb","ccc"}
res=tb1+tb2
for i,v in ipairs(res) do
print(v)
end
print()
function mt.__unm(a)
local result = setmetatable({},mt)
for i=#a , 1 ,-1 do
table.insert(result,a[i])
end
return result
end
res=-tb1+tb2
for i,v in ipairs(res) do
print(v)
end
print()
function mt.__tostring(a)
local result = "{"
for i,v in ipairs(a) do
result = result.." "..v
end
result = result.." } "
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"
运行结果:

0
1
4
5
true
alpha
beta
gamma
aaa
bbb
ccc
gamma
beta
alpha
aaa
bbb
ccc
{ alpha beta gamma }
there is no fsy in the table
nil
lua: my_test.lua:166: Stop laugh!
stack traceback:
[C]: in function 'error'
my_test.lua:160: in function
my_test.lua:166: in main chunk
[C]: ?
作者最新文章
漫蛙漫画最新版本下载
2026-10-13 13:20
漫蛙漫画官方免费漫画入口
2026-10-13 13:19
漫蛙漫画网页版入口
2026-10-13 13:19
最新漫蛙链接合集2026
2026-10-13 13:16
漫蛙manwa2登录网址
2026-10-13 13:14
热门文章
更多
精品专题
更多
Mac软件
更多
WINDOWS
更多










































