quick-cocos-2dx学习之【init.lua】

init.lua的学习开始,看大师是怎么对接口进行二次封装的~

1、

local ok, socket = pcall(function()

  return require("socket")

end)

if ok then

  math.randomseed(socket.gettime() * 1000)

else

  math.randomseed(os.time())

end

math.random()

math.random()

math.random()

math.random()

上面代码的意图是:

创建一个socket,创建成功的话,ok = true,失败则ok = false。

创建成功的话,就用socket来获取时间,然后拿来作为随机种子,否则用os的time()方法来创建随机种子。

socket与os的差别在于,socket的对时间的获取精度更高(0.001s),os的精度则在秒(0.01s)。

然后random了四次。。。(听说因为Lua中的random方法在首次random时,有bug,所以。。。)

2、

if type(DEBUG) ~= "number" then DEBUG = 1 end

local CURRENT_MODULE_NAME = ...

cc = cc or {}

cc.PACKAGE_NAME = string.sub(CURRENT_MODULE_NAME, 1, -6)

cc.VERSION = "2.2.0"

cc.FRAMEWORK_NAME = "quick-cocos2d-x client"

require(cc.PACKAGE_NAME .. ".debug")

require(cc.PACKAGE_NAME .. ".functions")

require(cc.PACKAGE_NAME .. ".cocos2dx")

echoInfo("")

echoInfo("# DEBUG = "..DEBUG)

echoInfo("#")

device = require(cc.PACKAGE_NAME .. ".device")

transition = require(cc.PACKAGE_NAME .. ".transition")

display = require(cc.PACKAGE_NAME .. ".display")

audio = require(cc.PACKAGE_NAME .. ".audio")

network = require(cc.PACKAGE_NAME .. ".network")

ui = require(cc.PACKAGE_NAME .. ".ui")

crypto = require(cc.PACKAGE_NAME .. ".crypto")

json = require(cc.PACKAGE_NAME .. ".json")

上面代码的意思是:如果DEBUG变量不是number的话,就设置值为1。

CURRENT_MODULE_NAME = ... 是为了获取当前lua文件的require路径,

假设有个文件夹app下有文件myapp.lua,那么此时的"..."的值:app.myapp

所以这个文件的表示应该是xxx.yyy.init

然后分割了下串,去除了尾部的.init,此时同一个文件夹下面的lua文件就可以正常require了,

像下面三行require的那种表示形式,表示require了与init.lua同文件夹下面的三个.lua文件。

然后echo打印控制台了下,接着可以看到我们常用的熟悉的身影了(device,audio,display...他们就是通过这种方式加载进来的)

3、

if not NO_EXTENSIONS then

  require(cc.PACKAGE_NAME .. ".cc.init")

end

if not NO_SHORTCODES then

  require(cc.PACKAGE_NAME .. ".shortcodes")

end

local sharedTextureCache = CCTextureCache:sharedTextureCache()

local sharedDirector = CCDirector:sharedDirector()

local function showMemoryUsage()

  echoInfo(string.format("LUA VM MEMORY USED: %0.2f KB", collectgarbage("count")))

end

if DEBUG_FPS then

  sharedDirector:setDisplayStats(true)

end

if DEBUG_MEM then

  sharedDirector:getScheduler():scheduleScriptFunc(showMemoryUsage, 10.0, false)

end

上面的代码:首先把需要包含的文件require进来,用短名命名TextureCache和Director,

然后根据相关的标志位,打开FPS,打开垃圾显示,每过10秒显示一次lua的内存信息。