Lua程序設計之————Lua面向對象1
阿新 • • 發佈:2017-06-04
pre cal oca () cti 輸出 alt 想象 完整
完整代碼
local mt = {} mt.__add = function(t1,t2) print("兩個Table 相加的時候會調用我") end local t1 = {} local t2 = {} -- 給兩個table 設置新的元表,一個元表就是一個table的值 setmetatable(t1,mt) -- meta:元素 setmetatable(t2,mt) -- 進行相加操作 local t = t1 + t2 print(t) --[[輸出結果 兩個Table 相加的時候會調用我 nil --]]
完整代碼
-- 創建一個元表 (是創建一個類嗎?) local mt= {} mt.__add = function(s1, s2) local result = "" if s1.sex == "boy" and s2.sex == "girl" then result = "一個男孩和一個女孩的家庭" elseif s1.sex == "girl" and s2.sex == "girl" then result = "兩個女孩的家庭" else result = "未知孩子的家庭" end return result end -- 創建兩個table,可以想象成是兩個類的對象(實例化兩個類) local s1= { name = "Per1", sex = "boy" } local s2 = { name = "Per2", sex = "girl" } -- 給兩個table 設置新的元表,一個元表就是一個table的值 setmetatable(s1, mt) setmetatable(s2, mt) -- 進行加法操作 local result = s1 + s2 print(result) -- 一個男孩和一個女孩的家庭
----------------------------------------------------------- Lua面向對象2 local t= { name = "Tinywan" } local mt = { __index = function(table,key) print("雖然你調用了我不存在的字段和方法,不過沒關系,我能檢測出來"..key) end } setmetatable(t,mt) print(t.name) print(t.age)
--[[輸出結果 Tinywan 雖然你調用了我不存在的字段和方法,不過沒關系,我能檢測出來age nil --]]
----------------------------------------------------------- Lua面向對象2 local t = { name = "Tinywan" } local mt = { money = 808080 } mt.__index = mt setmetatable(t,mt) print(t.money) -- 輸出結果 808080
----------------------------------------------------------- Lua面向對象2 local t = { name = "Tinywan" } local mt = { __index = { money = 909090 } } setmetatable(t,mt) print(t.money) -- 輸出結果 909090
----------------------------------------------------------- Lua面向對象2 local smartMan = { name = "Tinywan", age = 26, money = 800000, say_fun = function() print("Tinywan say 大家好") end } local t1 = {} local t2 = {} local mt = { __index = smartMan } -- __index 可以是一個函數,也可以是一個函數 setmetatable(t1, mt) setmetatable(t2, mt) print(t1.money) t2.say_fun() --- 輸出結果 -- 800000 -- Tinywan say 大家好
Lua程序設計之————Lua面向對象1