1. 元表 metatable
首先了解一下元表 meta_table
当索引一个key时,普通表中没有,就会到元表的__index中寻找。pairs访问__index会报错。
-- 定义一个普通的表
local normal_tab = { key3 = 4 }
-- 定义一个元表
local meta_tab = {
__index = {
["key1"] = 1,
[0] = 2,
key2 = 3
},
key4 = 5
}
-- 让meta_tab成为normal_tab的元表
setmetatable(normal_tab, meta_tab)
print(normal_tab["key1"])
print(normal_tab[0])
print(normal_tab.key2)
print(normal_tab.key4)
print(meta_tab.key4)
for k,v in pairs(normal_tab) do
print("normal_tab " .. k .. " " .. v)
end
2.表table中函数使用dot、colon符号中的self
dot定义的函数如果不显式传递self,就无法找到正确的对象;colon定义的函数既可以在第一个参数显式传递self,亦可以隐式传递。
PS:使用colon定义的函数用dot符号调用如果不显式传递自己,无法正确获得对象。
local temp = {}
function temp.test(self)
print("dot function")
print(self)
end
function temp:test1()
print("temp function ")
print(self)
end
temp.test(temp) -- 显式传递
temp:test1() -- 隐式传递
temp:test1(temp) -- 显式传递
temp.test1(temp) -- 显式传递
3.面向对象思想的实现,以Person类为例
local person = {
name = "",
sex = "",
age = 0,
}
--[[ 实现一, 在self中直接创建__index表
function person:new(object)
if not object then
object = {}
end
setmetatable(object, self)
self.__index = self
return object
end
]]
-- 实现二, 创建一个空元表,__index直接指向self
function person:new(object)
if not object then
object = {}
end
setmetatable(object, { __index = self })
return object
end
function person:printf()
print("person call " .. self.name .. " " .. self.sex .. " " .. self.age)
end
function person:identity()
print("self table addr ", self)
end
local man = person:new({
name = "shakker2c",
sex = 'male',
age = 22
})
-- 重载
function man:printf()
print("man call " .. self.name .. " " .. self.sex .. " " .. self.age)
end
-- print(man.name .. " " .. man.sex .. " " .. man.age)
man:printf()
man:identity()
man.identity(man)
print("man table addr ", man)
local woman = person:new({
name = "feshakker",
sex = 'female',
age = 22
})
-- 重载
-- function woman:printf()
-- print("woman call " .. self.name .. " " .. self.sex .. " " .. self.age)
-- end
-- print(woman.name .. " " .. woman.sex .. " " .. woman.age)
woman:printf()
woman:identity()
woman.identity(woman)
print("woman table addr ", woman)