lua语法学习1

--   -- run
 --   local sceneGame = cc.Scene:create()
 --   sceneGame:addChild(createLayerFarm())
 --   sceneGame:addChild(createLayerMenu())

--if cc.Director:getInstance():getRunningScene() then
-- cc.Director:getInstance():replaceScene(sceneGame)
--else
-- cc.Director:getInstance():runWithScene(sceneGame)
--end
   cclog("----------------------------------------")


   --local nhang = 1 / 3
   --local nNumber = (1 % 3) * 200
   --local X = nNumber
   --local Y = nhang * 100
     --   nhang = nhang - nhang%1
     --   print("ddddddd")
     --   local a, b = math.modf(1/10)
     --   print(a)
     --   print(b)
     --   Map = {1,2,3}


     --   for id, name in next, Map do
     --      print(id, name)               -- 返回的时候用括号括起来表示返回的参数
     --   end 


     --local uiLayout = GUIReader:shareReader():widgetFromJsonFile("DemoLogin/DemoLogin.ExportJson")


     --local a = 1
     --assert( a == 2 , "dugaoda assert")
     --cclog("next")
     --local t = next(tMy)
     --cclog("next%d", t)
     --cclog("unpack")
     
     --cclog("unpack")
     ---- 闭包的概念
     local __index123 = function () return 1  end
     local value = __index123()  -- value 1
     local __index1 = function (a) return (1 + a)  end
     local value1 = __index1(2)  -- value1  3
     local pointer = __index123  -- 指向__index123这个函数
     cclog("pointer()")
     print(pointer())
     --print(pointer(2))
     pointer = __index1
     cclog("pointer(2)")
     print(pointer(2))


     --local temptable = {"du", "gao", "da"}
     --table.concat(temptable, ";", 1, 2)  -- du:gao
     --local table2 = {[1] = "a", [2] = "b", [3] = "c", [26] = "z"}
     --table.maxn(table2)  -- 会返回26


     --local meta = 
     --{
     --  __add = function (op1, op2)
     --       op ={}
     --       op.x = op1.x + op2.x
     --       op.y = op1.y + op2.y
     --       return op
     --       end
     --}
     ---- meta 变化的意思
     --local a = { x = 1, y = 2 }
     --setmetatable(a, meta)
     --local b = { x = 2, y = 3}
     --c = a + b
     --print("add realize")
     --print(c.x, c.y)  -- 输出3 5




-------------------------- 2015年1月22日 --------------------------


     -- 使用cocos2d中extern中的class
     local MySprite = class("MySprite", 
                     function(fileName)
                        return CCSprite:create(fileName) 
                     end
     )
     
     MySprite.__index = MySprite
     MySprite.type1 = 0


     function MySprite:createMS(fileName, _type)
         local mySprite = MySprite.new(fileName)
         mySprite:myInit(_type)
         return mySprite
     end


     function MySprite:myInit(_type)
         self.type1 = _type
     end


     local ddds = MySprite:createMS("menu2.png", 1)
     ddds:setPosition(ccp(100, 100))
     --sceneGame:addChild(ddds, 100)


     -- 创建layer
     local DuGaoDaLayer = class("DuGaoDaLayer", 
                          function ()
                              return CCLayer:create()
                          end                                  
     )
     DuGaoDaLayer.__index = DuGaoDaLayer  -- 其实这句貌似这里可以不用写 在创建的其实就已经给DuGaoDaLayer设置元表
     DuGaoDaLayer.H = 10   -- 新增成员变量
     DuGaoDaLayer.W = 20   -- 新增成员变量


     -- 模仿他们的创建函数 实例对象
     function DuGaoDaLayer:create()
             local layer = DuGaoDaLayer.new()
             --layer:setH(1)
             return layer
     end


     -- 新增函数
     function DuGaoDaLayer:setH(nHeight)
        self.H = nHeight
     end


     -- 创建
     local templayer = DuGaoDaLayer:create()
     -- 以后函数的创建或调用统一使用:           只有成员变量调用的时候才使用.  自己在创建和调用的时候老是调用.
     templayer:setH(1) 
     print("dugaodalayer")
     print(templayer.H)
     print(templayer.W)






     Window = {}
     Window.prototype = {x = 0, y = 0, width = 100, heiht = 100}
     Window.mt = {}
     --Window.td ={}
     function Window.new(o)
         setmetatable(o, Window.mt)
         return o
     end
     Window.mt.__index = function(table, key)   -- 这里的元方法是函数
         return Window.prototype[key]
     end


     local w = Window.new({x = 10, y = 20})
     print(w.width)   -- 100


     -- 元表的使用
     -- 定义一个表 
     ManDuGaoDa = {}
     ManDuGaoDaSon = {}
     ManDuGaoDaSon.info = {name = "duxiaoda", age = 10}
     ManDuGaoDa.mt = {}  -- 创建元表


     setmetatable(ManDuGaoDa, ManDuGaoDa.mt)  
     --ManDuGaoDa.mt.__index = function(table, Key)    -- 实现元表中的内容
     --   return ManDuGaoDaSon.info[Key] 
     --end 
     --或写成  
     ManDuGaoDa.mt.__index = ManDuGaoDaSon.info  -- 在这里ManDuGaoDaSon.info称为元方法
     print(ManDuGaoDa.name)  -- 输出 duxiaoda 
     print(ManDuGaoDa.age)   -- 输出 10




     -- lua类的使用
     -- 1.定义表
     dugaoda = {garde = 0}
     -- 2.模拟构造体
     function dugaoda:new(o)
         local o = o or {}
         setmetatable(o, self)
         self.__index = self
         return o
     end
     
     function dugaoda:play()
        print("dugaoda")
     end
     function dugaoda:test1()
        print("test1")
     end
     function dugaoda:test2()
        print("test2")
     end
     -- dugaoda的实例dugaoda1
     dugaoda1 = dugaoda:new()  
     -- 重新定义基类的方法play
     function dugaoda1:play()
        print("dugaoda1")
     end
     -- dugaoda1的实例dugaoda2
     dugaoda2 = dugaoda1:new()   -- 这里把dugaoda1当作dugaoda的子类使用
     print(dugaoda2.garde)       -- 输出 0
     dugaoda2.garde = 10
     print(dugaoda2.garde)       -- 输出 10
     --print(dugaoda2.garde())   -- 错误 这是成员不是方法
     dugaoda2:play()             -- 输出 dugaoda1
     dugaoda2:test1()            -- 输出 test1
     dugaoda2:test2()            -- 输出 test2




     -- 另一种方式类,带有成员方法的并且初始化成员方法
     dugaodafamily = {nfather = 0, nmother = 0, nson = 0, nwife = 0}
     dugaodafamily.__index = dugaodafamily


     function dugaodafamily:new(father, mother, son, wife)
         local self = {}
         setmetatable(self, dugaodafamily)  -- 设置 元方法是dugaodafamily,dugaodafamily是table也可以是函数
         self.nfather = father
         self.nmother = mother
         self.nson = son
         self.nwife = wife
         return self
     end


     clonedugaoda = dugaodafamily:new(1, 2, 3, 4)
     print(clonedugaoda.nfather)
     print(clonedugaoda.nmother)
     print(clonedugaoda.nson)
     print(clonedugaoda.nwife)


     print("------------------- coroutine -----------------------------")
     -- 协同程序
     local co = coroutine.create(function () print("coroutine running") end) --创建新的协同程序
     print(coroutine.status(co)) -- 输出co的状态  现在是suspended
     coroutine.resume(co)       -- coroutine running
     -- coroutine.yield()


     local cotest = coroutine.create(function ()
           for i = 1, 10 do
               print("co", i)
               coroutine.yield()
           end
     end)


     coroutine.status(cotest)  -- 查看
     coroutine.resume(cotest)  -- 唤起 
     coroutine.status(cotest)  -- 查看
     coroutine.resume(cotest)  -- 再次唤起


    coroutine.resume(cotest)     -- 打印co 3
    coroutine.resume(cotest)     -- 打印co 4
    coroutine.resume(cotest)     -- 打印co 5
    coroutine.resume(cotest)     -- 打印co 6
    coroutine.resume(cotest)     -- 打印co 7
    coroutine.resume(cotest)     -- 打印co 8
    coroutine.resume(cotest)     -- 打印co 9
    coroutine.resume(cotest)     -- 打印co 10
    coroutine.resume(cotest)     -- 什么都不打印
    print(coroutine.status(cotest))     -- dead


    local co1 = coroutine.create(function ()
        for i = 1, 5 do
            print("dugaoda hp:", i)
            coroutine.yield(co1)
        end
        print("stop hp +")
    end)
    coroutine.resume(co1)   -- 1
    coroutine.status(co1)


    coroutine.resume(co1)   -- 2
    coroutine.status(co1)


    coroutine.resume(co1)   -- 3
    coroutine.status(co1)


    coroutine.resume(co1)   -- 4
    coroutine.status(co1)


    coroutine.resume(co1)   -- 5
    coroutine.status(co1)


    coroutine.resume(co1)  -- 已经死亡无法唤起
    print(coroutine.status(co1))  -- dead




    local co2 = coroutine.create(function (name)
        print(name)
        for i = 1, 10 do
            coroutine.yield("dugaoda give")
        end
    end)


    local result, msg = coroutine.resume(co2, "du")  -- 其实这边得到的是 coroutine.yield("dugaoda give")返回的结果和信息
    print(msg)
    local result, msg = coroutine.resume(co2)
    print(msg)
    local result, msg = coroutine.resume(co2)
    print(msg)


    function foo (a)
        print("foo", a)  -- foo 2
        return coroutine.yield(2 * a) -- return 2 * a
    end
 
    co = coroutine.create(function (a , b)
        print("co-body", a, b) -- co-body 1 10
        local r = foo(a + 1)
 
        print("co-body2", r)
        local r, s = coroutine.yield(a + b, a - b)
 
        print("co-body3", r, s)
        return b, "end"
    end)
 
    print("main", coroutine.resume(co, 1, 10)) -- true, 4
    print("------")
    print("main", coroutine.resume(co, "r")) -- true 11 -9
    print("------")
    print("main", coroutine.resume(co, "x", "y")) -- true 10 end
    print("------")
    print("main", coroutine.resume(co, "x", "y")) -- false cannot resume dead coroutine
    print("------")
    
    --     -- 基类
    --Account = {balance = 0}


    --function Account.new(o)
  -- o = o or {}
  -- setmetable(o, self)
  -- self.__index = self
  -- return o
    --end


    --function Account:desposit(v)
    --     self.balance = self.balance + v
    --end


    ---- 子类
    --SpeciallAccount = Account:new()


    ---- 实例子类对象
    --a = SepciallAccount:new(1000.00)


    --Person = { name = "这个人很懒" }
    --Person.talk = function ( self , words )
    --print ( self.name .. "说:" .. words )
    --end
    --Person:talk("你好")


     --    local meta = 
     --{
     --  talek = function ()
     --       return print("a")
     --       end
     --}
     ---- meta 变化的意思
     --local a = {}
     --setmetatable(a, meta)
     --a.talek()


     --local MyLayer = class("MyLayer", function()
     --return CCLayer:create()
     --end)
-------------------------- 2015年1月22日 --------------------------
-- 错误处理,程序终止,不会执行下去,会输出如下提示


-- error
    --error("你的智商不多了,赶紧休息,恢复一下吧")
-- 如果assert的第一个参数为不为false,则返回第一个参数的值;否则,执行error函数,输出错误信息,错误信息的内容为assert的第二个参数。
    --assert(false, "你是一个非常善良有爱心的人,我很喜欢你..所以,去死吧!")
-- 使用pcall调用test函数,如果test不报错,则pcall返回ture,否则,返回false。
   function test()
       print("dugaoda true")
   end
   if pcall(test) then
       print("normal")
   else
       print("error")
   end




   -- 函数的几个特别之处  函数参数个数自适应
   function dugaodamethod(sNmae, nAge)
       print(sNmae)
       print(nAge)
   end


   dugaodamethod("dugaoda")
   dugaodamethod("dugdaoda", 40, 20, "hello")


   function dugaodareturn()
       return 10, 20
   end
   local a, b, c = 10, dugaodareturn() -- 输出 10 10 20
   -- 函数的特点之一:如果函数的调用不是在表达式的最后一个元素,则最多只返回一个值
   local a, b, c = dugaodareturn(), 10 -- 输出 10 10 nil
   print(a)
   print(b)
   print(c)
   -- 具名实参
   function dugaodainfo1(args)
       return args.name, args,age
   end
   -- 是根据table的key值来获取的,根本就不需要考虑参数顺序
   local sname, nage = dugaodainfo1({name = "dugaoda", age = 30})




-- 非局部变量
    function myclosure()
       local i = 0     -- 在这里i属于非局部变量
       return function ()
              i = i + 1
              return i
              end 
    end
    local mydiaoyong = myclosure()   -- myclosure()函数的返回值是一个匿名函数,这里要特别的注意mydiaoyong对应的值是myclosure()的返回值匿名函数
    -- 相当于 mydiaoyong = function () i = i + 1 return i end 
    -- 当执行 local mydiaoyong = myclosure() 的时候其实运行了myclosure()函数里面的内容对i赋了初0
    -- 执行mydiaoyong()的时候其实相当于执行匿名函数里面的内容 返回得到i的内容
    print(mydiaoyong()) -- 1
    print(mydiaoyong()) -- 2
    print(mydiaoyong()) -- 3


    --在这里,local i就属于一个非局部变量,因为它既不是全局变量,也不是单纯的局部变量(因为另外一个函数可以访问到它)。
    --再来回到定义,count函数里的那个函数,加上非局部变量i,就构成了一个闭合函数了,就这么简单。
    --对于闭合函数而言,属于它的非局部变量,并不是在调用它的时候临时产生的,而是和它一起存在的。
    --所以每次调用闭合函数,非局部变量的值都不会被重置。


   function myclosure1()
       return function ()
              local ni = 123     -- 在这里ni属于局部变量
              ni = ni + 1
              return ni
              end 
   end


   local temp = myclosure1()
   print(temp())   -- 输出123
   print(temp())   -- 输出123
   print(temp())   -- 输出123


   -- 介绍一个“语法糖”
   function dugaodayufa()
   end
   -- 等价于  上下两个等价
   local dugaodayufa
   dugaodayufa = function()
   end


   -- 这样就不会报错了 du1能够识别到du2
   local du1
   local du2
   local function du1()
       return du2()
   end
   local function du2()
       print("23")
   end


   -- 尾调用
   -- 尾调用的大致意思是:一个函数的调用是另一个函数的最后一个动作时,这个调用就称之为尾调用。
   function foo1()
       return foo()
   end


   --这就不属于尾调用,因为调用完count函数之后,还要取得count的返回值,然后进行一次加法操作
   function foo2()
       return foo() + 1
   end


    function foo234(n)
        if n > 0 then
            return foo234(n - 1)
        else
            return "dugaoda"
        end
    end
    local p = foo234(5)
    print(p)


    --  迭代器 打算2015年1月23日 看一遍  
    local tabTest = {du, gao, da, ha, ha, ha}
    for index, value in ipairs(tabTest) do
        print(value)
    end


    function mydiedaiqi(t)
        local i = 0
        return function()
            i = i + 1
            return t[i]
        end
    end


    local iter = mydiedaiqi(tabTest)
    -- 实现1
    while true do
        local value = iter()
        if value == nil then
            break
        end
        print(value)
    end
    -- 实现2
    for value in mydiedaiqi(tabTest) do
        print(value)
    end




    function a(...)
        local arg = {...}
    end


    -- 字符串部分


    -- require (用于使用模块)
    -- module (用于创建模块)
    print("require dugaoda")
    --require("src/dugaoda")
    require("src/dugaoda")  --
    -- 都可以正常的调用dugaoda.lua 中的MAX_DUGAODA_SIZE和hesls()变量和函数 ,如果dugaoda.lua中的变量或方法有关键字local那么就会调用不到
    print(MAX_DUGAODA_SIZE)
    hesls()
    -- 包含模块文件
    local dugaodason1 = require("dugaodason")
    dugaodason1.info()


    --pay()
    -- 其实,require干的事就是这样:(这就是为什么模块文件要写成那样了)
    --local dugaodason1 = (function()
    ---- dugaodason.lua的内容
    --end)


-------------- 模块(module)和包(package) --------------


    -- require会将返回值存储到table package.loaded中


    require("dugaodabigson")
    --pay() -- 错误  程序识别不到pay这个函数必须加上前缀dugaodabigson
    dugaodabigson.pay() -- 正确




    --简单的说
    --a.lua
    --module (..., package.seeall)
    --flag=true
    --function example()
    --...
    --end
    --在别的脚本中
    --require "a"


    --调用脚本a中的任何全局变量或者函数必须加上a.
    --这个好处就是你不同的脚本中可以用相同的名称定义变量或者函数,而不会混乱。
-------------- 模块(module)和包(package) --------------


    -- Lua中的捕获机制和转换技巧介绍
    local getstr = "dugaoda = memeda"
    local _, _, key, vale = string.find(getstr, "(%a+)%s*=%s*(%a+)")
    -- 存储哑元变量 _ 中
    -- '%a+' 表示非空的字母序列;'%s*' 表示0个或多个空白  %[对应符号[  %]对应符号%] 貌似也可以用\[ \]
    local date = "17/7/1990"
    local month, day, year = string.find(date, "(%d+)/(%d+)/(%d+)")
    -- 假定你想查找一个字符串中单引号或者双引号引起来的子串,你可能使用模式 '["'].-["']',
    local s = [[then he said: "it's all right"!]]




    -- Lua中handler方法的原理详解
    print("-------------- handler --------------")
    local dugaodahandler = {}
    function dugaodahandler:fun()
        self.m = "hello"  
    end
    local dugaodahandler1 = {}
    dugaodahandler.fun(dugaodahandler1)  -- 因为fun函数里面执行的内容是 dugaodahandler1.m = "hello"  替代了self
    
    print(dugaodahandler1.m)  -- hello
    print(dugaodahandler.m)   -- nil
    --handler(cls, cls.onClose)


    function fandlertemp(obj, method)
        return function(...)
            return method(obj, ...)
        end
    end


    local cls = {}
    cls._m = "close"
    function cls:onClose()
        print(self._m)
    end
     
    fandlertemp(cls, cls.onClose)()   -- 分析
    --local sdie = fandlertemp(cls, cls.onClose)  -- 结果sdie = function(...) return method(obj, ...) end
    --sdie()  -- 执行 method(obj, ...) 函数   cls:onClose() print(cls._m)
    
    --+      匹配前一字符1次或多次
    --*      匹配前一字符0次或多次
    ---      匹配前一字符0次或多次
    --?      匹配前一字符0次或1次


    -- 另外的2中循环
    local conditon = 5
    while conditon == 5 do
        print("de")
        conditon = 1
    end


    repeat
        print("de")
        conditon = 5
    until conditon == 5




    local di = {2,2,3}
    local sd = next(di)  -- 返回第一个索引的值 可以用next(t)来检测表是否为空(此函数只能用于以数字索引的表与ipairs相类似)
    print(sd)  -- 输出1
    local myceil = math.ceil(3.1)
    print(myceil)  -- 输出4


    --randomseed --设随机数种子 math.randomseed(os.time())  
    --random --取随机数 math.random(5,90) 5~90
    --modf 取整数和小数部分 math.modf(20.12) 20   0.12
    --mod 取模 math.mod(65535, 2) 1
    local str1 = string.char(97) -- 转换整数为相对应的字符
    print(str1)
    -- Lua中实现面向对象的一种漂亮解决方案
    local _class={}
 
    function class(super)
        local class_type = {}
        class_type.ctor = false -- 设置构造函数
        class_type.super = super -- 设置父类


        class_type.new = function(...) -- 
            local obj = {}
            do
            local create
            create = function(c,...)
                    if c.super then
                        create(c.super, ...)
                    end
                    if c.ctor then
                        c.ctor(obj, ...)
                    end
            end
 
            create(class_type, ...)
        end


        setmetatable(obj, { __index = _class[class_type] })
        return obj
        end


        local vtbl = {}
        _class[class_type] = vtbl
 
        setmetatable(class_type, {__newindex = function(t, k, v) vtbl[k] = v end })
 
        if super then
            setmetatable(vtbl,{ __index = function(t,k) 
            local ret=_class[super][k]
            vtbl[k]=ret
            return ret
            end
            }
            )
        end
 
        return class_type
    end




    base_type = class()  -- 定义一个基类 base_type


    function base_type:ctor(a)  -- 定义 base_type 的构造函数
        print("base_type ctor")
        self.m_a = a
    end


    function base_type:print_a()  -- 定义一个成员函数
        print(self.m_a)
    end


    function base_type:hello()  -- 定义另一个成员函数 base_type:hello
        print("hello base_type")
    end
    


    jichenglei = class(base_type) -- 定义一个类 jichenglei 继承于 basetype


    function jichenglei:ctor()    -- 定义 jichenglei 的构造函数
        print("jichenglei ctor")
    end


    function jichenglei:hello()   -- 重载 base_type:hello 为 jichenglei:hello
        print("hello jichenglei")
    end


    myjicheng = jichenglei.new(2)
    myjicheng:print_a()
    print("class")






    --Lua教程之弱引用table
    --1.无法超越人类智慧的智能——自动内存管理的缺陷
    t = {}


    key1 = {name = "du"}
    t[key1] = 1
    key1 = nil


    key2 = {name = "gao"}
    t[key2] = 2
    key2 = nil


    -- 强制进行一次垃圾收集
    --collectgarbage();  -- 单词barbage垃圾的意思


    for Key, Value in pairs(t) do
        print(Key.name .. ": " .. Value)
    end


    --2.颠覆你的认知——弱引用table
    --刚刚举例的只是正常情况,那么,如果我们把某个table作为另一个table的key值后,希望当table设为nil值时,另一个table的那一条字段也被删除。
    --应该如何实现?
    --这时候就要用到弱引用table了,弱引用table的实现也是利用了元表。


    weak_t = {}


    -- 给t设置一个元表,增加__mode元方法,赋值为“k”
    setmetatable(weak_t, {__mode = "k"});


    weak_key1 = {name = "my"}
    weak_t[weak_key1] = 1
    weak_key1 = nil


    weak_key2 = {name = "wife"}
    weak_t[weak_key2] = 2
    weak_key2 = nil


    -- 强制进行一次垃圾收集
    --collectgarbage();  -- 单词barbage垃圾的意思
    -- 这时候weak_t已经是一个空的table了
    if next(weak_t) then
        print("exist")
    else
        print("null")
    end
    print("weak_reference")
    for Key, Value in pairs(weak_t) do
        print(Key.name .. ": " .. Value)  -- 这个时候输出的结果为空
    end


    --    3.三种形式的弱引用


    --对于弱引用table,其实有三种形式:


    --1)key值弱引用,也就是刚刚说到的情况,只要其他地方没有对key值引用,那么,table自身的这个字段也会被删除。设置方法:setmetatable(t, {__mode = “k”});
    --2)value值弱引用,情况类似,只要其他地方没有对value值引用,那么,table的这个value所在的字段也会被删除。设置方法:setmetatable(t, {__mode = “v”});
    --3)key和value弱引用,规则一样,但是key和value都同时生效,任意一个起作用时都会导致table的字段被删除。设置方法:setmetatable(t, {__mode = “kv”});


    local value1 = "du"
    local value2 = "gao"
    local key1 = 1
    local key2 = 2
    weak_t_v = {}
    setmetatable(weak_t_v, {__mode = "k"});
    weak_t_v[key1] = value1
    weak_t_v[key2] = value2


    key1 = nil
    key2 = nil


    for Key, Value in pairs(weak_t_v) do
        print(Value)
    end


    print("collectgarbage")
    --collectgarbage()


    --for Key, Value in pairs(weak_t_v) do
    --    print(Value)
    --end


    -- 上面不管是对 value1=nil 或 key1 = nil  都无法把表给清空 因为只对table有效


    local value11 = {name = "du"}
    local value22 = {name = "gao"}


    weak_t_v2 = {}
    setmetatable(weak_t_v2, {__mode = "v"});
    weak_t_v2[1] = value11
    weak_t_v2[2] = value22


    value11 = nil
    value22 = nil


    for Key, Value in pairs(weak_t_v2) do
        print(Value)
    end


    print("collectgarbage")
    collectgarbage()
    -- 这个时候table已经是空的了
    if next(weak_t_v2) then
        print("exist")
    else
        print("null")  
    end


    for Key, Value in pairs(weak_t_v2) do
        print(Value)  -- 输出 table
        print(Value.name)  -- 输出 table
    end


   -- 语法小技巧
   local x = x or v
   local  x = a and b or c
   local a = b == "dugaoda" --


   --2015年1月30日 10:07:00
   local num16_1 = 0x56
   local num16_2 = 0xff
   print(num16_1)
   print(num16_2)


   --注:前面说过,Lua中的变量,如果没有local关键字,全都是全局变量,Lua也是用Table来管理全局变量的,Lua把这些全局变量放在了一个叫“_G”的Table里。


    --__add(a, b)                     对应表达式 a + b
    --__sub(a, b)                     对应表达式 a - b
    --__mul(a, b)                     对应表达式 a * b
    --__div(a, b)                     对应表达式 a / b
    --__mod(a, b)                     对应表达式 a % b
    --__pow(a, b)                     对应表达式 a ^ b
    --__unm(a)                        对应表达式 -a
    --__concat(a, b)                  对应表达式 a .. b
    --__len(a)                        对应表达式 #a
    --__eq(a, b)                      对应表达式 a == b
    --__lt(a, b)                      对应表达式 a < b
    --__le(a, b)                      对应表达式 a <= b
    --__index(a, b)                   对应表达式 a.b
    --__newindex(a, b, c)             对应表达式 a.b = c
    --__call(a, ...)                  对应表达式 a(...)


    local table1 = {1, 2}
    local table2 = {2, 3}
    local metameathon = 
    {
    __add = function(a, b)  -- 重载加号运算符 
            temp = {}
            temp[1] = a[1] - b[1]
            temp[2] = a[2] - b[2]
            return temp
        end
    }
    setmetatable(table1, metameathon)
    local table3 = table1 + table2
    for Key, Value in ipairs(table3) do
        print(Value)    -- 输出 -1 -1
    end


    
    local table12 = {[1] = "a", [2] = "b", [3] = "c", [26] = "z"}
    local mymxan = table.maxn(table12)  -- 
    print(mymxan)  -- 输出26


    -- 升序排列
    local tbl = {"du", "gao", "da", "ha"}
    table.sort(tbl)
    print(table.concat(tbl, ":"))


    local tab23 = {10, 20, 39, 392}
    table.sort(tab23) 
    print(table.concat(tab23, ":"))


    local guild1 = {}


    table.insert(guild1, {
    name = "Cladhaire",
     class = "Rogue",
      level = 70,
    })


    table.insert(guild1, {
     name = "Sagart",
     class = "Priest",
      level = 70,
    })


    table.insert(guild1, {
    name = "Mallaithe",
    class = "Warlock",
    level = 40,
    })


    mysortmethon = function(a, b)
        if a.level == b.level then
            return a.name < b.name
        else
            return a.level < b.level
        end
    end
    table.sort(guild1, mysortmethon)
    for Key, Value in ipairs(guild1) do
        print(Value.name)
    end


    --tolua.isnull是判断一个userdata是否存在或者已经被释放的。如果传入的参数不是userdata,当然会返回true。 
    local p1 = tolua.isnull("sdfe")  -- 返回true
    local p2 = tolua.isnull(null)    -- 返回true
    local p3 = tolua.isnull({})      -- 返回true


    --2015年2月2日 09:07:29
    local table123 = {3, 234, 45, xing  = "du", ming = "gao", 2340, 92, 10, wifi = "mima"}


    table.foreachi(table123, function(i, v) print(v) end) -- 只输出数字的数字key
    table.foreach(table123, function(i, v) print(v) end) -- 输出整个表


    -- 返回从一个unix时间值
    -- 10800 = 3*60*60 (3 hours) 向西3个时区
    print(os.time{year=1970, month=1, day=1, hour=0})  --> 10800  


     -- 返回当前用户机器上的时间.
    local timetemp = os.date("*t", 906000490)
    -- timetemp = {year = 1998, month = 9, day = 16, yday = 259, wday = 4,
    -- hour = 23, min = 48, sec = 10, isdst = false}
    print(os.date("%x", 906000490))
    --> 09/16/1998
    --函数os.clock返回执行该程序CPU花去的时钟秒数
    --getfenv(function or integer) - 返回此表已获取函数的堆栈结构或者堆栈等级
    --setfenv(function or integer, table) - 设置此表已获取函数的堆栈结构或者堆栈等级

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值