Lua中「 」以及 物件導向

2021-08-19 17:28:58 字數 2860 閱讀 1514

閱讀本文需要理解前一篇文章lua中的元方法

當通過:呼叫時,系統會自動傳遞當前的table給self,例如a.eat(a)相當於a:eat()

傳遞當前物件給eat方法,這樣就提高了table的方法的擴充套件性了。

-- 本質是使用table進行模擬

​--定義空表,相當於是乙個類

person = {}

​---定義區域性表引用變數,降低方法引用表字段的耦合性

this =person

--定義字段

person.name="bob"

person.gender = "男"

person.age = 18

​--定義方法

--第一種第一方式(匿名函式)

person.speak = function()

print("人在說話")

end​

--第二種

function person.walking()

print("人在走路")

end​

--方法中呼叫方法

function person:showinfo()

print("呼叫個人資訊")

print("name:"..this.name)

print("age:"..this.age)

end​

--使用self關鍵字 函式使用":"定義函式

function person:show()

print("呼叫個人資訊")

print("name:"..self.name)

print("age:"..self.age)

end​

--呼叫

print(person.name)

print(person.gender)

print(person.age)

person.speak()

person.walking()

​a = person

person = nil

a.showinfo()

​--相當於a.showinfo(a)

a:showinfo()

在一中我們解決了表的方法的通用性問題,但我們想解決建立乙個新的person表物件,又得重寫乙個表,重新賦值,非常麻煩。所以在lua中我們先定義好乙個原型,通過定義乙個new方法,可以很方便的建立乙個原型物件(在lua中還是乙個表)。

player = 

for k,v in pairs(player) do

p[k] = v

endreturn p

end,

​ --錯誤示範一

--move = function(x,y)

-- player.x = player.x + x

-- player.y = player.y +y

--end

​ --方法一

--[[ move = function(p,x,y)

p.x = p.x+x

p.y = p.y +y

end]]​​

}--方法二 self要配合「:」使用

function player:move(x,y)

self.x = self.x +x

self.y = self.y +y

endp1 = player.new()

p1.x = 10;

p1.y = 20;

p1.name = "bob"

​p2 = player.new()

p2.x = 30;

p2.y = 40;

p2.name = "steve"

​print(p1.x,p1.y,p1.name)

print(p2.x,p2.y,p2.name)

​--這裡表示了「:」的意思,把本身當做引數傳遞進去

p1:move(10,10)

p2:move(10,10)

​print(p1.x,p1.y,p1.name)

print(p2.x,p2.y,p2.name)

原理是通過__index方法,當表中沒有查詢到key值時,就會去元表中查詢。

person = 

setmetatable(tab, person)

tab.name = name

tab.age = age

return tab

end;

tostring = function(self)

print(self.name, self.age)

end;

work = function(self)

print(self.name .. "的工作是養老")

end;

}---這句話放在外表確保先執行 重建person

person.__index = person;

father= person.new("yeye", 99)

father:tostring()

father:work()

print(getmetatable(father).name)

son = father.new("son",18)

son:tostring()

son:work()

--son son中含有work方法 就會直接返回

function son:work()

print(self.name.."我的工作是開車")

endson:work()

print(getmetatable(son).name)

lua中的物件導向

lua中是通過元表來物件導向的,下面就lua物件導向做一下說明 local account function account new o 這裡是冒號哦 o o or 如果使用者沒有提供table,則建立乙個 setmetatable o,self self.index self return o e...

lua物件導向

直接貼 參考的也是別人的,只不過其中幾點,增加一點自己的理解 local baseclass print baseclass是 tostring baseclass 定義index屬性,指向本身 baseclass.index baseclass 定義建構函式 function baseclass ...

Lua 物件導向

記錄學習過程 建立日期 2019 04 14 物件由屬性和方法組成。lua中最基本的結構是table,所以需要用table來描述物件的屬性。lua 中的 function 可以用來表示方法。那麼lua中的類可以通過 table function 模擬出來。乙個簡單的物件導向例子 屬性 person ...