嗚嗚喔學習筆記: 1月 2016

搜尋此網誌

2016年1月25日 星期一

Sample Lua OOP(1)

創建一個
簡單的類別
功能包含

public function 
private functionc
constructor

程式碼:

程式碼: main.lua
local dog = require "Dog" --引入類別

local BigDog = dog.New( "Apple" , 10 ) --創建物件 

local SmallDog = dog.New( "Orange" , 4 )

BigDog:Bark()
BigDog:PrintAge()
SmallDog:Bark()
SmallDog:PrintAge()



程式碼: Dog.lua
local Object = {}

-------------------------------------------------
-- GLOBAL
-------------------------------------------------

function Object.New( name , ageInYears )-- constructor
 local self = 
 {
  name = name ,
  age = ageInYears 
 }

 -------------------------------------------------
 -- PRIVATE FUNCTIONS
 -------------------------------------------------

 local function GetDogYears( realYears ) -- local; only visible in this module
  return realYears * 7
 end

 -------------------------------------------------
 -- PUBLIC FUNCTIONS
 -------------------------------------------------

 function self:Bark()
            print( self.name .. " says \"woof!\"" )
 end

 function self:PrintAge()
     print( self.name .. " is " .. GetDogYears( self.age ) .. " in dog years." )
 end

 return self 

end

return Object

輸出結果:

1月 26 01:14:56.748: Apple says "woof!"
1月 26 01:14:56.748: Apple is 70 in dog years.
1月 26 01:14:56.748: Orange says "woof!"
1月 26 01:14:56.748: Orange is 28 in dog years.




2016年1月6日 星期三

產生唯一碼(GUID , UUID) (Lua 版本)


Guid 

主要能夠產生唯一碼 的原因就是樣本數夠大
有 2^128 種可能 

在真正隨機產生亂數的情況下 
幾乎不可能產生同樣的編碼

程式碼:

---------------------
--產生GUID
--範例:
--[[
 local guid = require( "Tool.Guid")

 print("guid.NewHex" , guid.NewHex())
 print("guid.NewLong" , guid.NewLong())
]]--

---------------------

local M = {}

--樣本數為 2^128
function M.NewHex()
    --隨機種子
    local d = io.open("/dev/urandom", "r"):read(4)
    local template ="xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
    math.randomseed(os.time() + d:byte(1) + (d:byte(2) * 256) + (d:byte(3) * 65536) + (d:byte(4) * 4294967296))
    return string.upper(string.gsub(template, "x", 
        function (c)
            local v = (c == "x") and math.random(0, 0xf) or math.random(8, 0xb)
                    return string.format("%x", v)
            end))
end

--樣本數為 2147483647
function M.NewLong()
    --隨機種子
    local d = io.open("/dev/urandom", "r"):read(4)
    math.randomseed(os.time() + d:byte(1) + (d:byte(2) * 256) + (d:byte(3) * 65536) + (d:byte(4) * 4294967296))
    return math.random( 1 , 2147483647 )
end
return M