lua學習筆記

備註:部分參考笨木頭的博客(http://www.benmutou.com/archives/1844),很不錯。


1、

-- 獲取table的最小值
--function GetMin(theTable)
--  myString="minValue=math.min("
--  
--  for i,v in pairs(theTable) do
--    myString=string.format("%s%d%s",myString,v,",")
--  end
--  myString=string.sub(myString,1,string.len(myString)-1)
--  myString=string.format("%s%s",myString,")")
--  
--  assert(loadstring(myString))()
--  return minValue
--end

--字符串替換
--myString="happy,hello,home"
--myString=string.gsub(myString,"h%a+","GG",2)
--print(myString)



--    function dieDaiQi(t)
--        local i = 0;
--        return function()
--            i = i + 1;            
--            return t[i];
--        end
--    end

--    function dieDaiQi(t)
--        local i = 0;
--        return function()
--            i = i + 1;   
--            if i>#t then 
--            return nil,nil
--            end         
--            return i,t[i];
--        end
--    end


--    local t = {"fdsd", "445"};
--    for i,value in dieDaiQi(t) do
--        print(i..":"..value);
--    end



--local co=coroutine.create(function() print("hello") end)
--coroutine.resume(co)

--print(dofile("src/luaTex.lua"));





--------元表的操作---------------
local a={sex="boy"}
local b={sex="girl"}

local mt={}
--加法操作
mt.__add=function(a,b)
  if a.sex=="boy" and b.sex=="girl" then
    result="good"
  elseif a.sex=="girl" and b.sex=="girl" then
    result="so good"
  else
    result="shit"
  end
  return result
end
--保護元表
mt.__metatable="sorry,you can not change this model"

--查找不到的方法操作
--mt.__index=function(table,key)
--  print("給不了你要的:"..key)
--end

--備胎屬性
mt.__index={
firstName="handsome",
name="you are a bad boy"
}

----------------------------------
--這就是__newindex的規則:
--a.如果__newindex是一個函數,則在給table不存在的字段賦值時,會調用這個函數。
--b.如果__newindex是一個table,則在給table不存在的字段賦值時,會直接給__newindex的table賦值。
--用於監控更新
--mt.__newindex=function(table,key,value)
--  print(key.."不存在")
--end
local other={
--我們給a的name賦值的時候,實際上是給other的name賦值了。
  name="other name"
}
mt.__newindex=other

setmetatable(a,mt)
setmetatable(b,mt)


--print(getmetatable(a))

local result=a+b
print(result)

a.name="good boy..."
print(a.name)
--print(other.name)
--使用rawget和rawset可以忽略掉元表的__index和__newindex作用,相當於並不存在__index和__newindex元方法
print(rawget(a,"name"))
rawset(a,"name","after name..")
print(rawget(a,"name"))
print("----------------------------分水線------------------------")
print("\n\n")

print("---------------只讀table----------------")
local readOnly=function(t)
  local newt={}
  local mt={
    __index=t,
    __newindex=function()
      error("只能讀,不能改哦")
    end
  }
  setmetatable(newt,mt)
  return newt
end

local days=readOnly({"星期一","星期二","星期日"})
print(days[2])
--使用rawset,則打破了限制
rawset(days,2,"222")
print(days[2])
print("---------------只讀table----------------")
print("\n\n")

print("----------------------------非局部變量和局部變量------------------------")
--    -- 定義一個全局變量
--    gName = "哎喲,很挫哦";
--    -- 將當前全局環境重新設置爲新的table
--    setfenv(1, {g = _G});
--    -- 輸出值
--    g.print(gName);
--    -- 再次定義一個全局變量
--    gName = "哎喲,有點錯哦";
--    -- 再次輸出值
--    g.print(gName);
--    -- 輸出原來的值
--    g.print(g.gName);
--    g.print("----(1)----")

gName="哈哈"
local newG={}
setmetatable(newG,{__index=_G})
setfenv(1,newG)
for _,v in pairs(newG) do
  print("**"..v)
end
gName="哈哈..."
for _,v in pairs(newG) do
  print("**"..v)
end
print(gName)
print("------(2)使用__index-------")


local game=require("src/luaTex")
game.say()









2、

--冒號的作用就是:定義函數時,給函數的添加隱藏的第一個參數self;調用函數時,默認把當前調用者作爲第一個參數傳遞進去。
--使用了冒號之後,就相當於我們剛剛使用點號時一樣,只是我們不再需要顯式地定義self參數以及主動地傳遞tmp_people參數。
people={
name="xm",
age=25,
--setInfo=function(self,n,a)
--  self.name=n
--  self.age=a
--end
}

function people:setInfo(n,a)
  self.name=n
  self.age=a
end

function people:getInfo()
  print("name:"..self.name.."    age:"..self.age)
end


--people.setInfo("datou",30)
--people.getInfo()



tmp_people=people
--print(people.name)
--tmp_people.name="xxx"
--print(people.name)

people=nil
print(tmp_people:getInfo())













3、

--面向對象
People={
x=0,
y=0
}

function People:setPosition(x,y)
  self.x=x
  self.y=y
end

function People:new()
  o={}
--  setmetatable(o,{__index=self})
--  進行優化,避免每次都創建元表
    setmetatable(o,self)
    self.__index=self
  return o
end


--使用People進行new,所以self存的是People
local p1=People:new()
local p2=People:new()
p1:setPosition(11,22)
p2:setPosition(33,44)
print(p1.x.."   "..p1.y)
print(p2.x.."   "..p2.y)
--函數的重載
function p1:setPosition(x,y)
  print("p1的重寫函數")
end
p1:setPosition(8,8)
print(p1.x.."   "..p1.y)
print("----------------------")

--使用p1進行new,所以self存的是p1
local p1_1=p1:new()
p1_1:setPosition(88,99)
print(p1_1.x.."   "..p1_1.y)









4、

--多繼承

--(1)多繼承之在多個類(即table)中查找一個字段
function search(classes,key)
  for i=1,#classes do
    local value=classes[i][key]
    if value~=nil then
      return value
    end
  end
end

local t1={name="xx"}
local t2={name="oo",age=25}
--print(search({t1,t2},"name"))
print(search({t1,t2},"age"))


--(2)多繼承之創建繼承多個類的子類
function createExtendsClass(...)
  local parents={...}
  local child={}

--設置類元素(也就是從多個繼承類中查找一個元素)
setmetatable(child,{
__index=function(table,key)
  return search(parents,key)
end
})

--給類增加創建對象的方法
function child:new()
  o={}
  setmetatable(o,child)
  child.__index=child
  return o
end

  return child
end




tt1={name="kitty"}
function tt1:hello()
  print("hello,everyone")
end
function tt1:new()
  o={}
  setmetatable(o,self)
  self.__index=self
  return o
end



tt2={name="tom"}
function tt2:fire()
  print("hello,start fire")
end
function tt2:new()
  o={}
  setmetatable(o,self)
  self.__index=self
  return o
end

--繼承兩個類的子類
local extendsT=createExtendsClass(tt1,tt2)
--子類對象
local tmp_extend=extendsT:new()
tmp_extend:hello()
tmp_extend:fire()
print(tmp_extend.name)


print("-------------弱引用table----------------")
--t={}
--key2 = {name = "key2"}
--t[key2] = 1
--for i,v in pairs(t) do
--print(i.name..":"..v)
--end

t = {};
-- 給t設置一個元表,增加__mode元方法,賦值爲“k”
setmetatable(t, {__mode = "k"});
-- 使用一個table作爲t的key值
key1 = {name = "key1"};
t[key1] = 1;
    --key值弱引用
    key1 = nil;
    --value值弱引用
    --t[key1]=nil    
    --key和value值弱引用
    -- setmetatable(t, {__mode = "kv"});   

-- 又使用一個table作爲t的key值
key2 = {name = "key2"};
t[key2] = 1;
key2 = nil;
-- 強制進行一次垃圾收集
collectgarbage();
for key, value in pairs(t) do
  print(key.name .. ":" .. value);
end



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章