面向对象类闭包示例

lua-users home
wiki

-- example class
Class = {
  
  -- class vars
  class_var = 123,
  
  -- ctor
  new = function()
    local self = {}
    
    -- member vars
    self.member_var = 456
    
    -- methods
    self.method = function()
      self.member_var = self.member_var + 1
    end
    
    return self
  end,
  
  -- static methods
  static_method = function()
  end,
}

-- example derived class
DerivedClass = {
  new = function()
    self = Class.new() -- base class
    
    -- override a method
    self.method = function()
      self.member_var = self.member_var + 2
    end
    
    return self
  end,
}

-- example usage
obj = DerivedClass.new()
obj.method()
print(obj.member_var)

最近更改 · 偏好设置
编辑 · 历史记录
最后编辑于 2011 年 5 月 4 日上午 8:32 GMT (差异)