LUA Private function 和 Private 變數

LUA 的private 變數作法如下

local function MyClass(init)
  -- the new instance
  local self = {
    -- public fields go in the instance table
    public_field = 0
  }

  -- private fields are implemented using locals
  -- they are faster than table access, and are truly private, so the code that uses your class can't get them
  local private_field = init

  function self.foo()
    return self.public_field + private_field
  end

  function self.bar()
    private_field = private_field + 1
  end

  -- return the instance
  return self
end

local i = MyClass(5)
print(i.foo()) --> 5
i.public_field = 3
i.bar()
print(i.foo()) --> 9

而private function 的作法如下,嚴格來跟C語言的OOP的私有函數還是不太一樣的觀念,

local function MyClass(init)
    -- the new instance
    local self = {
        -- public fields go in the instance table
        public_field = 0
    }

    -- private fields are implemented using locals
    -- they are faster than table access, and are truly private, so the code that uses your class can't get them
    local private_field = init

    function self.foo()
        return self.public_field + private_field
    end
    local function privatefunction2()
        private_field = private_field + 10
    end
    function self.bar()
        private_field = private_field + 1
        local function privatefunction()
           private_field = private_field + 10
        end
        privatefunction()
        privatefunction2()
    end
    

    -- return the instance
    return self
end

    local i = MyClass(5)
    print(i.foo()) --> 5
    i.public_field = 3
    i.bar()
    print(i.foo()) --> 29
   -- print(i.privatefunction2()) --> 因為是私有函數,所以無法被呼叫
    

Screen Shot 2015-07-04 at 11.55.27 AM

柯老師的範例程式可以在此下載

參考資料在此

更多完整的LUA  OOP 參考資料在此