1. 程式人生 > >Lua面向對象 --- 單例

Lua面向對象 --- 單例

工程 ret style new sin let CA pre The

工程目錄結構:

技術分享圖片

GameManager.lua:

 1 --單例模式是利用一個全局表來實現的
 2 
 3 GameManager = {}
 4 
 5 Manager = {__index = GameManager}
 6 
 7 function GameManager:new()
 8     local self = {}
 9     setmetatable(self,Manager)
10     return self
11 end
12 
13 function GameManager:ShowName()
14     print("the is an singleton
") 15 end

Main.lua:

 1 require "GameManager"
 2 
 3 gm = GameManager:new()
 4 
 5 gm:ShowName()
 6 
 7 --[[
 8 運行結果:
 9 the is an singleton
10 --]]

碼雲上的相關工程:https://gitee.com/luguoshuai/LearnLua

Lua面向對象 --- 單例