Reputation: 8130
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
I'm using a linter and its complaining that I'm using the colon unnecessarily for my update
and exit
methods. The reason I do this is to keep all my methods uniform. Sometimes I need self
and sometimes I don't.
But in general is there any advantage to using colon on these at all? It seems like if i have something like State:start
then I could just reference State
directly. I could do State.attackTimer
vs self.attackTimer
..
Why would you ever really need the colon? If you have access to the table that holds the method then you have access to self.. right?
Upvotes: 2
Views: 117
Reputation: 5031
The :
syntax is a great tool when you are making a class using a table and a metatable.
Your code above, rather then creating a class, creates an encapsulated set of functions. which have access to State
as an upvalue.
I will use this class from Lua Users - SimpleLuaClasses as an example:
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)
Here we have an instance(acc
) of the Account
class. To adjust or modify the values in this specific instance of Account
we can not refer to Account.balance
inside of Account:withdraw
. We need a reference to the table where the data is stored, and that is where passing that table using :
comes in.
acc:withdraw(100)
is just syntactic sugar for acc.withdraw(acc, 100)
passing in our table as the first param self
. When you define Account:withdraw(amount)
there is an implicate first variable self
the definition could be written as Account.withdraw(self, amount)
Upvotes: 3