[英]Question about when to use lua colon syntax
local Public = {}
function Public.new(ent)
local State = {}
function State:update(player)
ent:setLinearVelocity(0,0)
end
function State:start(player)
ent.fixedRotation = true
self.attackTimer = _G.m.addTimer(200, function()
ent:setState('attacking', player)
end)
end
function State:exit(player)
ent.fixedRotation = false
timer.cancel(self.attackTimer)
end
return State
end
return Public
我使用的是linter,它抱怨我的update
和exit
方法不必要地使用了冒號。 我這樣做的原因是使我的所有方法保持一致。 有時我需要self
,有時我不需要。
但是總的來說,在所有這些上使用冒號是否有任何優勢? 好像我有State:start
類的東西,那么我可以直接引用State
。 我可以做State.attackTimer
與self.attackTimer
..
為什么您真的需要結腸? 如果您可以訪問保存該方法的表,那么您可以訪問self ..對嗎?
當使用表和元表創建類時, :
語法是一個很好的工具。
上面的代碼創建了一組封裝的函數,而不是創建一個類。 可以將State
視為高價值。
我將以Lua Users-SimpleLuaClasses中的此類為例:
Account = {}
Account.__index = Account
function Account:create(balance)
local acnt = {} -- our new object
setmetatable(acnt,Account) -- make Account handle lookup
acnt.balance = balance -- initialize our object
return acnt
end
function Account:withdraw(amount)
self.balance = self.balance - amount
end
-- create and use an Account
acc = Account:create(1000)
acc:withdraw(100)
這里我們有一個Account
類的實例( acc
)。 要調整或修改此Account
特定實例中的值,我們不能引用Account:withdraw
內的Account.balance
。 我們需要引用存儲數據的表,也就是使用:
傳遞該表的地方。
acc:withdraw(100)
只是acc.withdraw(acc, 100)
語法糖, acc.withdraw(acc, 100)
作為第一個參數self
傳入我們的表中。 定義Account:withdraw(amount)
會有一個隱式第一個變量self
該定義可以寫為Account.withdraw(self, amount)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.