简体   繁体   中英

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

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?

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM