Lua面向对象 --- 单例

工程目录结构:

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

猜你喜欢

转载自www.cnblogs.com/luguoshuai/p/9228580.html