自学Lua的脚印(为自己)

---------------Lua For Windows 5.1-----------------------


--[[
local a = {x =function() print('a do') end}
local b = {x =function() print("b do") end}


setmetatable(a, {__index = b})


--a.x = nil
a.x()




local str = 'name =
--'s' "qqq"'--"name = 'qqq'"
print(str)


]]


--[[
function deepChildSearch(...)
  local arg = {...}
  print('------'..arg[1]) 
  print('------'..arg[2]) 
  print(arg[3]) 
end


deepChildSearch('a', 'b')
--]]


--[[
--声明,这里声明了类名还有属性,并且给出了属性的初始值。
LuaClass = {x = 0, y = 0}


--这句是重定义元表的索引,就是说有了这句,这个才是一个类。
-- LuaClass.__index = LuaClass


--构造体,构造体的名字是随便起的,习惯性改为New()
function LuaClass:New(x, y) 
    local self = {};    --初始化self,如果没有这句,那么类所建立的对象改变,其他对象都会改变
    setmetatable(self, {__index = LuaClass});  --将self的元表设定为Class
    self.x = x;
    self.y = y;
    return self;    --返回自身
end


local obj = LuaClass:New(3,4)


--测试打印方法--
function LuaClass:test() 
    print("x:>" , self.x , " y:>" , self.y);
end


obj:test()
--endregion


--]]


--[[
-- 数组 表。。测试。。---------
--Arrays
myData={}
myData[0] = "foo"
myData[1] = 20
--Hash tables
myData["bar"] = "baz"
--structure
for key,value in pairs(myData) do
print(key,"=", value)
end
-- 数组 表。。测试。。---------
--]]


--[[
---  表嵌套。。测试。。---------
-- table constructor
myPolygon ={
color = 'blue',
thickness = 2,
npoints = 4,
{x = 0, y =0},
{x = -10, y = 0},
{x = -5, y = 4},
{x = 0, y = 4}
}
print(myPolygon['color'])
print(myPolygon.color)
print(myPolygon[2].x)


--for key,value in pairs(myData) do
-- print(key,"=", value)
--end
----  表嵌套。。测试。。---------
--]]


--[[
-- 表的相互引用赋值。。测试。。---------
a ={}
a['x'] = 10
b=a
print(b['x'])
b['x'] = 20
print(a['x'])
a= nil
print(b['x'])
b= nil
print(b['x'])
-- 表的相互引用赋值。。测试。。---------
--]]


--[[
-- 不定参数。。测试。。---------
function fun_print(...)
for i=1,arg.n do
print("fun_print",type(arg),arg[i])
end
end


fun_print("One", "Two")
-- 不定参数。。测试。。---------
--]]


--[[
-- 以table作为参数。。测试。。---------
function fun_print(t)
print(t.Length,#t,table.maxn(t))
for k,v in pairs(t) do
print(k..'='..v)
end
print('adfasdfasdfasdfda')
end


fun_print{["a"] = 10, ["b"] = 20, ["c"] = 25}
--fun_print{[1] = 10, [2] = 20, [4] = 25}
--fun_print{['a'] = 10, [2] = 20, [4] = 25}
--fun_print{['a'] = 10, [1] = 20, [3] = 25}
-- 不定参数。。测试。。---------
--]]


--[[
-- table循环。。测试。。---------
tbtest ={[1] = 1,[100] = 2}
local count =0
--for i=1, table.maxn(tbtest) do
-- count = count + 1
-- print(tbtest[i])
--end


--for k,v in pairs(tbtest) do
--for k,v in ipairs(tbtest) do
-- count = count + 1
-- print(k..'='..v)
--end


for i=1, #(tbtest) do
count = count + 1
print(tbtest[i])
end


print('count', count)


-- table循环。。测试。。---------
--]]


--[[
-- while repeat循环。。测试。。---------
local a = 0
--while true do
-- a = a + 1
-- if a>= 10 then
-- print('break a', a)
-- break;
-- else
-- print('a', a)
-- end
--end


repeat 
a = a + 1
print('a', a)
until a>=10


-- while repeat循环。。测试。。---------
--]]


--[[
-- Lua 类型和值。。测试。。---------
print(type("Hello world")) 
print(type(10.4*3))
print(type(print))
print(type(type))
print(type(true))
print(type(nil))
print(type(boolean))
print(type(number))
print(type(string))
print(type(userdata))
--print(type(function))
print(type(thread))
print(type(table))
print("------------------------------------------------")
print ('10' + 1) -- 11
--print('hello' + 1) ---attempt to perform arithmetic on a string value
print(10 .. 20) ----1020
print(10 == tonumber('10'))----true
print(10 == '10') ---false
print(10 == tonumber('a2'))----false
print("----------+++++++++++++++++++++------------")
print('a' < 'b') ----true
--print(2 < '3') ----attempt to compare number with string
print('2' < '3') ----true
local a = nil
print(a == nil) -----true
print(nil == nil) -----true
----两个值类型不同,lua认为两者不同,nil只和自己相等, lua的引用比较table,userdata,function,
----当且仅当两者表示同一对象时相等,也就是内存地址一样 , 数字比较按传统数字比较,字符串按字母顺序
----进行,但是字母顺序依赖于本地环境, 混合比较数字和字符串Lua会报错
a = {}; a.x = 1; a.y = 0;
b = {}; b.x = 1; b.y = 0;
c = a
print(a == c, a, c) --- true
print(a == b, a, b) --- false
print("------------------------------------------------")
----只有false和nil是假(false),其他为真,0也是true,a and b的时候,a为true返回b,a为false返回a。
----a or b 的时候,a为true返回a,a为false返回b, not 的结果一直返回false或true
print(4 and 5)  ----5
print(nil and 5)  ----nil
print(false and 5)  ----false
print(0 and 5)  ----5
print(4 or 5)  ----4
print(false or 5)  ----5


---- x = x or v 等价于 if not x then x = v end
---- a ? b : c  Lua中实现 (a and b) or c
print(not nil) ---- true
print(not false) ---- true
print(not 0) ----false
print(not not nil) ----false


---- Lua中的运算符的从高到低的顺序
---- ^
---- not -(unary 表示负)
---- * /
---- + -(减法)
---- ..
---- < > <= >= ~= ==
---- and
---- or
-- Lua 类型和值。。测试。。---------
--]]


--[[
-- Lua 表。。测试。。---------
--a = {x = 0, y = 0}    等价于   a = {}; a.x = 0; a.y = 0; 
--不管用何种方式创建table,我们都可以向表中添加或删除任何数据类型的域,构造函数仅仅影响表的初始化
--------------------------------------------------------
--x = {math.sin(4), math.sin(1), math.sin(2)} ---- if not math  so "attempt to call global 'sin' (a nil value)"
w = {x = 1, y = 2, label = 'console'} ----, [x] = 'aaaa' so “ table index is nil”  Lua中key值可以是除了nil以外的表,字符串,数字,函数
--['x'] = 1 相当于 x = 1
--w = {z = 1, y = 2, label = 'console'; x = {a = 3, b= 4}} 
x = {math.sin(4), math.sin(1), math.sin(2)} ---- if not math  so "attempt to call global 'sin' (a nil value)"
print('w[1]', w[1]) ----nil  如果w的初始化中有 ; [1] = 'aaaa' 就会打印出aaaa了
for k,v in pairs(w) do
-- print('for_a: '..k..'\t'..type(k))
end
w[1] = 'another field'
x.f = w
for k,v in pairs(w) do
-- print('for_b: '..k..'\t'..type(k))
end
print('value_type :', type(w[x]), type(w['x']), 'key_type:', type(x), type('x'))
print('w[x]', w[x]) ----nil    ---如果把x的表的声明,放到w表的声明之前,并且 w表中x =1 改成 [x] = 1这个就能取到, 而下边w['x']则是nil
print("w['x']", w['x']) ----1
print('w[1]', w[1]) ----another field
print('x.f[1]', x.f[1]) ----another field
w.x = nil
print("w['x']", w['x']) ----nil
--------------------------------------------------------
------------------------------------------
list = nil
for line in io.lines() do
list = {next = list, value = line}
end
print('list_count:', #list)
for k,v in pairs(list) do
print('for_a: '..k..'\t'..type(k))
end
-----------------------------------------------
-- Lua 表。。测试。。---------
--]]


--[[
-- 用table为基础,实现了数组、链表、队列、集合等数据类型   测试。。---------


-- list = nil
-- for i=1, 10 do
-- list = {
-- next = list, 
-- value = i}
-- print('i: ', i, 'value', list[i])
-- end
-- local l = list
-- print(type(list), #l)
-- print(table.maxn(l))
-- local count = 0
-- while l do
-- count  = count + 1
-- l = l.next
-- print(count, l.value)  ----反序形成链表
-- end


--for i=1, l.Count do
--print(l[i])
--end


-- local t = {}
-- local str = io.read()
-- print(str)
-- for line in io.lines() do
--if(line == nil) then break end
--t[#t+1] = line
-- table.insert(t, line)
-- end
-- local s = table.concat(t,'\n') --
-- print(s)
--------------队列与双端队列-----------
-- List = {}
-- function List.New()
-- return {first = 0, last = -1}
-- end
-- function List.pushFront(list, value)
-- list.first = list.first - 1
-- print("list.first", list.first)
-- list[list.first] = value
-- end
-- function List.pushBack(list,value)
   -- list.last=list.last + 1
-- print("list.first", list.first)
   -- list[ list.last ]=value
-- end
-- function List.popFront(list)
-- local first = list.first
-- if first > list.last then error('List is Empty!') end
-- local value  = list[first]
-- list[first] = nil
-- list.first = first + 1
-- return value
-- end
-- function List.popBack(list)
   -- local last=list.last
   -- if last<list.first then error("List is empty!")
   -- end
   -- local value =list[last]
   -- list[last]=nil
   -- list.last=last - 1
   -- return value
-- end
-- lp = List.New()
-- List.pushFront(lp,1)
-- List.pushFront(lp,2)
-- List.pushBack(lp,-1)
-- List.pushBack(lp,-2)
-- print(#lp)
-- print('--------------------')
-- x = List.popFront(lp)
-- print(x) ---- 2
-- x=List.popBack(lp)
-- print(x) ---- -2
-- x=List.popFront(lp)
-- print(x) ---- 1
-- x=List.popBack(lp)
-- print(x) ---- -1
-- x=List.popBack(lp) ----error('List is Empty!')
-- print(x) ---- 不会走到这里了,上边开始检测到空
--------------队列与双端队列-----------
--------------二维数组-----------
-- local n = 10
-- local m = 10
-- local arr = {}
-- for i = 1, n do
-- arr[i] = {}
-- for j = 1, m do
-- arr[i][j] = i*j
-- end
-- end   
----string.format('%.2f', 数字) 保留小数点后两位
----string.format('%2d', 数字) 保留整数两位,如果不够空着, string.format('%02d', 数字),这样会用0填充
print(os.date()) ----03/28/17 09:57:20
local time1 = os.time()
print(time1) ----1490666240
print(os.date("%Y/%m/%d %H:%M:%S", time1)) ----2017/03/28 09:57:20
print(os.date("%X", time1)) ----09:57:20
print(os.date("*t", time1)) ----table: 004FB5B8
print(os.time{year = 2017, month = 3, day = 28}) ----1490673600
print(os.clock) ----function: 004F9040


local x = os.clock()
local s = 0
for i =1, 1000000 do s = s + i end
print(string.format("elapsed time: %.5f\n", os.clock() - x))
-- for i = 1, n do
-- for j = 1, m do
-- local num = string.format('%2d', arr[i][j])
-- if(j ~= m) then io.write(num..' ') ----不换行
-- else print('bb_'..arr[i][j]) ----借助换行
-- end
-- end
-- end
--------------二维数组-----------


-- 用table为基础,实现了数组、链表、队列、集合等数据类型   测试。。---------
--]]
--[[
----------------- 打印talbe表   测试。。---------
-- local print = print
-- local tconcat = table.concat
-- local tinsert = table.insert
-- local srep = string.rep
-- local type = type
-- local pairs = pairs
-- local tostring = tostring
-- local next = next
 
-- function print_r(root)
-- local cache = {  [root] = "." }
-- local function _dump(t,space,name)
-- local temp = {}
-- for k,v in pairs(t) do
-- local key = tostring(k)
-- if cache[v] then
-- tinsert(temp,"+" .. key .. " {" .. cache[v].."}")
-- elseif type(v) == "table" then
-- local new_key = name .. "." .. key
-- cache[v] = new_key
-- tinsert(temp,"+" .. key .. _dump(v,space .. (next(t,k) and "|" or " " ).. srep(" ",#key),new_key))
-- else
-- tinsert(temp,"+" .. key .. " [" .. tostring(v).."]")
-- end
-- end
-- return tconcat(temp,"\n"..space)
-- end
-- print(_dump(root, "",""))
-- end


 -- a = {}
-- a.a = { 
-- hello = { 
-- alpha = 1 ,
-- beta = 2,
-- },
-- world =  {
-- foo = "ooxx",
-- bar = "haha",
-- root = a,
-- },
-- }
-- a.b = { 
-- test = a.a 
-- }
-- a.c = a.a.hello
 
-- print_r(a)




a = { 
world =  {
foo = "ooxx",
bar = "haha",
root = a,
hello = { 
alpha = 1 ,
beta = 2,
hello2 = { 
alpha = 1 ,
beta = 2,
hello3 = { 
alpha = 1 ,
beta = 2,
hello4 = { 
alpha = 1 ,
beta = 2,
},
},
},
},
},
a = 2,
b='str'
}


function print_lua_table(lua_table, indent)
indent = indent or 0
for k, v in pairs(lua_table) do
if type(k) == "string" then
k = string.format("%q",k)
end
local szSuffix = ""
if type(v) == "table" then
szSuffix = "{"
end
local szPrefix = string.rep(" ", indent)
formatting = szPrefix.."["..k.."]".." = "..szSuffix
if type(v) == "table" then
print(formatting)
print_lua_table(v, indent + 1)
print(szPrefix.."},")
else
local szValue = ""
if type(v) == "string" then
szValue = string.format("%q", v)
else
szValue = tostring(v)
end
print(formatting..szValue..",")
end
end
end
print_lua_table(a, 2 )
----------------- 打印talbe表   测试。。---------
--]]
--[[
----------------- Lua 基本语法   测试。。---------
----a, b = 10, 2 * x   --相当于-- a = 10 ;b = 2 * x
-- a, b, c = 0, 1 
-- print(a, b, c) ------0       1       nil
-- a, b = a + 1, b + 1, b + 2
-- print(a, b) ------1       2
-- days = {'Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'}
-- revDays = {}
-- for i,v in pairs(days)do
-- revDays[v] = i
-- print(i, v, revDays[v])
-- end
---- 长短不一的缩进,是因为制表符 占位的问题
---- 1       Sunday  1
---- 2       Monday  2
---- 3       Tuesday 3
---- 4       Wednesday       4
---- 5       Thursday        5
---- 6       Friday  6
---- 7       Saturday        7
-------函数--------
-------调用函数的时候,如果参数列表为空,必须用()表明是函数调用,如果函数只有一个参数,并且这个参数是字符串或者表构造的时候,()是可选的
-- print "Hello World"   ---<-->---   print ("Hello World")
-- dofile 'a。lua'    ---<-->---   dofile('a.lua')
-- f{x = 10, y = 20}     ---<-->---   f({x = 10, y = 20})
-- type{}      ---<-->---   type({})
-- o:foo(x)     ---<-->---   o.foo(o, x)   ----面向对象方式调用函数方法
s, e = string.find("Hello Lua users", "Lua") ----返回匹配串“开始和结束的下标”,如果不存在返回nil
print(s, e) ----7       9
s, e = string.find("Hello Lua users Lua", "Lua") ----返回匹配串“开始和结束的下标”,如果不存在返回nil 找到第一个就返回了
print(s, e) ----7       9 
function maximun(a)
local mi = 1
local m = a[mi]
for i, val in ipairs(a) do
--print(i, val, m, mi)
if val > m then
mi = i
m = val
end
end
return m, mi
end
print(maximun{8,10,23,12,5}) ----23      3


function foo2() return 'a', 'b' end
x, y = foo2()
print(x, y) ----a       b
------用圆括号强制使调用返回一个值
print((foo2())) ----a  
f = string.find
a = {"Hello", "ll"}
------unpack 返回a所有元素作为f()的参数
print(unpack(a)) ----Hello   ll
print(f(unpack(a))) ----3       4


function fwrite(fmt,arg)
return io.write(string.format(fmt, unpack(arg)))
end
function g(a, b, args) 
print(a, b)
fwrite("%s,%s,%s,%s,%s", args)
end
g(1, 2, {3, 4, 5, 8, 10})
print('----------------------------')
local _, x = string.find("Hello Lua users Lua", "Lua")
print(x) ---- 我们只想用返回的第二个值, 使用虚变量(下划线)
function select1(n, ...)
return arg[n]
end
print(string.find("Hello hello hello", "hel")) ----7       9
print(select1(1, string.find("Hello hello hello", "hel"))) ----7
print(select1(2, string.find("Hello hello hello", "hel"))) ----9
print('----------------------------')
print('-------------external local variale 或者 upvalue  外部的局部变量-------') 
function newCounter()
local i = 0
return function()
i = i + 1
return i
end
end
c1 = newCounter()
print(c1()) ----1 -----如果c1不加(),则返回function: 0084D6A0
print(c1()) ----2
c2 = newCounter()
print(c2()) ----1  -----c1和c2是建立在同一个函数上,但作用在同一个局部变量的不同实例上的两个不同的闭包
print(c1()) ----3
print(c2()) ----2
print('----------内嵌函数,闭包,相当于c#中的static ------------------')
-----------闭包是一个内部函数,它可以访问一个或者多个外部函数的外部局部变量------------
function Fun1()
local iVal = 10
function InnerFunc1()
print(iVal)
--return iVal
end
function InnerFunc2()
iVal = iVal + 10
--return iVal
end
return InnerFunc1, InnerFunc2
end
local a, b = Fun1()   -------Fun1 一定加(),才能启动函数,否则仅仅是把函数Fun1的内存地址给a,b
a()
b()
a()
a = nil
b = nil
local a, b = Fun1()
a()
b()
a()
----------内嵌函数,闭包,相当于c#中的static ------------------
-------------external local variale 或者 upvalue  外部的局部变量  
-- print('----------函数作为talbe的域,eg. io.read math.sin  必须注意函数和表语法 ------------------')
-- Lib = {} ----表和函数放在一起
-- Lib.foo = function (x, y) return x + y end
-- Lib.goo = function (x, y) return x - y end
-- Lib = { ----使用表构造函数
-- foo = function (x, y) return x + y end
-- goo = function (x, y) return x - y end
-- }
-- Lib = {} ----函数保存在一个局部变量时,就得到一个局部函数,局部函数和局部变量一样在一定范围内有效,Lua 把chunk当作函数处理
-- function Lib.foo(x, y) return x + y end
-- function Lib.goo(x, y) return x - y end
-----在chunk内可以声明局部函数,仅仅在chunk内可见,词法定界保证了包内的其他函数可以调用此函数
-- local f = function(...) ... end
-- local g = function(...) 
-- ...
-- f()
-- ...
-- end
-- local function f (...)
-- ...
-- end
----------函数作为talbe的域,eg. io.read math.sin  必须注意函数和表语法  ------------------
print('----------递归函数的调用,必须在定义函数之前声明 ------------------')
local fact
fact = function (n)
if n == 0 then
return 1
else
return n * fact(n - 1)
end
end
print("Enter a numble")
local a = io.read("*number")
print(fact(a))
----------递归函数的调用,必须在定义函数之前声明 ------------------
-------尾调用不需要使用栈空间,那么尾调用递归的层次可以无限制的,
function foo(n) ---- 无论n为何值,不会导致栈溢出
if n > 0 then return foo(n - 1) end
end
function f(x) 
g(x)
return ----调用者函数调用其他函数后,没有做其他的事情,就不属于尾调用
end
------调用者f 在调用g后,不得不丢弃g的返回值,就不是尾调用
function f(x) 
return g(x) + 1  ---- must do then addition
end
function f(x) 
return x or g(x)  ---- must adjust to 1 result
end
function f(x) 
return (g(x))  ---- must adjust to 1 result
end
------调用者f 在调用g后,不得不丢弃g的返回值,就不是尾调用
function f(x) ------这个是尾调用
return x[i].foo(x[j] + a * b, i + j)  ---- Lua中类似return g(...)这种格式的调用是尾调用,但g和g的参数都可以是复杂表达式,因为Lua会在调用之前计算表达式的值
end
----------------------不是尾调用--stack overflow -------------------
function fun_r(a)
a = a + 1
print("a:", a)
if a > 100000 then
print(a)
else
fun_r(a)
end
return a
end
--local x = 1
--fun_r(x)
-----------------------不是尾调用--stack overflow -------------------
-------函数--------
----------------- Lua 基本语法   测试。。---------
--]]
--
----------------- Lua 迭代器与泛型for   测试。。---------
-- print('典型的闭包结构包含两个函数,一个是闭包自己,另一个是工厂(创建闭包函数)')
-- function list_iter(t)
-- local i = 0
-- local n = table.getn(t)
-- print('i', i, 'n', n)
-- return function()
-- i = i + 1
-- print('222_i', i, 'n', n)
-- if i <= n then return t[i] end
-- end
-- end
-- local t = {10, 20, 30}
-- local iter = list_iter(t) ----creates the iterator
-- while true do
-- local element = iter() ----calls the iterator
-- if element == nil then break end
-- print(element)
-- end
-- local t = {10, 20, 30}
-- for element in list_iter(t) do 
-- print(element)
-- end

-----------------------典型的闭包结构包含两个函数,一个是闭包自己,另一个是工厂(创建闭包函数)------------------

print('迭代器遍历一个文件里的所有匹配的单词')
function allWords()
-- local file = io.open("e:\\1t.txt", "r")
-- local str = file:read("*all")
-- file:close()
local file = io.input("e:\\1t.txt")
-- local str =  io.read("*all")
-- io.close(file)
--print(str)
local line = io.read("*all")
print(line)
local pos  = 1
return function()
while line do
local s, e = string.find(line, "%w+", pos)
if s then
pos = e + 1
return string.sub(line, s, e)
else
line = io.read()
pos = 1
end
end
return nil
end
end


-- for word in allWords() do
-- print(word)
-- end
-----------------迭代器遍历一个文件里的所有匹配的单词------------------
print('无状态迭代器')
local a = {'One','Two','Three'}
-- for i, v in ipairs(a) do
-- print(i, v)
-- end
function iter(a, i)
i = i + 1
local v = a[i]
if v then
return i, v
end
end
-- for i = 0, #a - 1 do
-- print(iter(a, i))
-- end
-----------------无状态迭代器------------------
print('多状态迭代器')
local iterator
function allwords()
local state = {line = io.read(), pos = 1}
end
function iterator(state)
while state.line do
local s, e = string.find(state.line, "%w+", state.pos)
if s then
state.pos = e + 1
return string.sub(state.line, s, e)
else
state.line = io.read()
state.pos = 1
end
end
return nil
end
---------------------尽量写无状态迭代器,次之使用闭包,最差使用table的多状态迭代器
-----------------多状态迭代器------------------
print('真正的迭代器')
function allWords(f)
for l in io.lines() do
for w in string.find(l, "%w+") do
f(w)
end
end
end
allWords(print) ----这样就可以打印了
-----------------真正的迭代器------------------
----------------- Lua 迭代器与泛型for   测试。。---------
--]]
--[[
----------------- Lua 编译运行调试   测试。。---------
print('loadstring 用于运行程序外部的代码,比如用户自定义的代码')
---------------loadstring 用于运行程序外部的代码,比如用户自定义的代码,loadstring期望一个chunk即语句---------------
---------------若要加载表达式,需要在表达式前加return,那样返回表达式的值-------------------
print('Enter you expression:')
-- local lNum = io.read("*number")
-- if not lNum then error("Invalid input") end
--local lNum = assert(io.read("*number"), "Invalid input") ----assert检查第一个参数是否返回错误,没错误就直接返回值,
-------------------------否则,以第二个参数抛出错误信息,第二个参数是可选的
local lNum = io.read()
assert(tonumber(lNum), "Invalid input  \"".. lNum.. "\"  is not a number")
local func = assert(loadstring('return '.. lNum))
print('the value of your expression is ', func())
for i = 1, 20 do
print(string.rep(i.."*", func()))
end
----------------- loadingstring 用于运行程序外部的代码,比如用户自定义的代码---------
----------------- require 的路径---------
-----------------require 是一个模式列表,每一个模式指明一种由虚文件名(require的参数)转成实文件名的方法。----------
--------------更明确地说,每一个模式包含可选的问号文件名,匹配的时候Lua首先将问号用虚文件名替换,然后看是否存在 ----
--------------若不存在继续用第二个模式匹配------------------
---------------   ?;?.lua;c:\windows\?;/user/local/lua/?/?.lua   ---------------------
------------require 保留一张已经加载的文件的列表,就避免了重复加载同一个文件两次,它保留的是文件的虚名而不是实文件名,---
------------如果 require "foo" 和 require "foo.lua" 也会加载两次,同样,_LOADED 访问文件名列表,手动让它加载两次,------
------------require "foo" 之后 _LOADED["foo"] 将不为nil,手动赋值为nil,再次require "foo",将会再次加载该文件 -------------
----------------- require 的路径---------
----error("abc", 2) ----error报告错误发生在第二级,你自己的函数是第一级
----print(debug.traceback())
----------------- Lua 编译运行调试   测试。。---------
--]]
--[[
----------------- Lua 协同程序   测试。。---------
--print('协同是一种非抢占式的多线程,协作的多线程')
-- local co = coroutine.create(function()
-- print("hi")
-- end)
-- print(co) ----thread: 0029CE30
-- print(coroutine.status(co)) ----suspended
-- coroutine.resume(co) ----hi
-- print(coroutine.status(co)) ----dead


-- local co = coroutine.create(function()
-- for i = 1, 3 do
-- print("hi", i)
-- coroutine.yield() 
-- ------函数yield使程序挂起,当再次激活挂起的程序时,yield返回并继续程序的执行知道再次遇到yield或程序结束--------
-- end
-- end)
-- print(coroutine.status(co)) ----suspended
-- coroutine.resume(co) ----hi      1
-- print(coroutine.status(co)) ----suspended
-- coroutine.resume(co) ----hi      2
-- print(coroutine.status(co)) ----suspended
-- coroutine.resume(co) ----hi      3
-- print(coroutine.status(co)) ----suspended
-- coroutine.resume(co) ----这个不会打印了
-- print(coroutine.status(co)) ----dead


--print('resume - yield 相互交换数据')
-----------------resume 没有相应的yield,resume把额外的参数传递给协同的主程序 -----------------
-- local co =  coroutine.create(function(a, b, c)
-- print(co, a, b, c)
-- end)
-- coroutine.resume(co, 1, 2, 3) ----nil     1       2       3
----------------------------------resume 返回除了true以外的其他部分将作为参数传递给相应的yield -----------------
-- local co =  coroutine.create(function(a, b)
-- coroutine.yield(a + b, a - b)
-- end)
-- print(coroutine.resume(co, 20, 10)) ----true    30      10
---------------------------------- yield返回的额外的参数也将会传递给resume -----------------
-- local co1 =  coroutine.create(function()
-- print(co1, coroutine.yield())
-- end)
-- coroutine.resume(co1)
-- coroutine.resume(co1, 4, 5) ----nil     4       5
-----------------resume - yield 相互交换数据--------------
---------------------------------- 当协同代码结束时主函数返回的值都会传递给相应的resume -----------------
-- local co =  coroutine.create(function()
-- return 6, 7
-- end)
-- print(coroutine.resume(co)) ----true    6       7
-----------------协同是一种非抢占式的多线程,协作的多线程---------------------
print('管道和过滤器')
function receive(prod)
local status, value = coroutine.resume(prod)
return value
end
function send(x)
coroutine.yield(x)
end
function producer()
return coroutine.create(function()
while true do
local x = io.read()
send(x)
end
end)
end
function filter(prod)
return coroutine.create(function()
local line = 1
while true do
local x = receive(prod)
x = string.format("%5d %s", line, x)
send(x)
line = line + 1
end
end)
end
function consumer(prod)
while true do
local x = receive(prod)
io.write(x, '\n')
end
end
--consumer(filter(producer())) ----类似UNIX的管道
-----------打印一个数组的所有的排列 (努力做高手) ------------
-- function permgen(a, n)
-- if n == 0 then
-- printResult(a)
-- else
-- for i = 1, n do
-- --print("----", i, n, a[i], a[n])
-- a[n], a[i] = a[i], a[n]
-- --print("b---", i, n, a[i], a[n])
-- permgen(a, n - 1)
-- --print("c---", i, n, a[i], a[n])
-- a[n], a[i] = a[i], a[n]
-- --print("d---", i, n, a[i], a[n])
-- end
-- end
-- end
-- function printResult(a)
-- for i, v in ipairs(a) do
-- io.write(v, " ")
-- end
-- io.write("\n")
-- end
-- permgen({1, 2, 3}, 3)--, 4


-------------用迭代器的协同 (努力做高手)---------
function permgen(a, n)
if n == 0 then
coroutine.yield(a)
else
for i = 1, n do
--print("----", i, n, a[i], a[n])
a[n], a[i] = a[i], a[n]
--print("b---", i, n, a[i], a[n])
permgen(a, n - 1)
--print("c---", i, n, a[i], a[n])
a[n], a[i] = a[i], a[n]
--print("d---", i, n, a[i], a[n])
end
end
end
function printResult(a)
for i, v in ipairs(a) do
io.write(v, " ")
end
io.write("\n")
end
function perm(a)
local n = table.getn(a)
-- local co = coroutine.create(function() permgen(a, n)end)
-- return function()
-- local code, res = coroutine.resume(co)
-- return res
-- end ----用Lua的wrap函数代替
return coroutine.wrap(function() permgen(a, n) end)
end
for p in perm{"a","b","c"}do
printResult(p)
end
------打印: 
-- -- b c a
-- -- c b a
-- -- c a b
-- -- a c b
-- -- b a c
-- -- a b c
-----------------管道和过滤器--------------
----------------- Lua 协同程序   测试。。---------
--]]
--[[
---------------------马尔可夫链算法---------------
function allWords()
-- -- local file = io.open("e:\\1t.txt", "r")
-- -- local str = file:read("*all")
-- -- file:close()
-- local file = io.input("e:\\1t.txt")
-- -- local str =  io.read("*all")
-- -- io.close(file)
-- --print(str)
-- local line = io.read("*all")
-- print(line)
local line = io.read()
local pos  = 1
return function()
while line do
local s, e = string.find(line, "%w+", pos)
if s then
pos = e + 1
return string.sub(line, s, e)
else
line = io.read()
pos = 1
end
end
return nil
end
end
function prefix(w1, w2)
return w1 ..' '..w2
end
local statetab
function insert(index, value)
if not statetab[index] then
statetab[index] = {n = 0}
end
table.insert(statetab[index], value)
end
local N = 2
local MAXGEN = 10000
local NOWORD = '\n'


statetab = {}
local w1, w2 = NOWORD, NOWORD
for w in allWords() do
insert(prefix(w1, w2), w)
w1 = w2; w2 = w;
end
insert(prefix(w1, w2), NOWORD)
w1 = NOWORD; w2 = NOWORD
for i = 1, MAXGEN do
local list = statetab[prefix(w1, w2)]
local r = math.random(table.getn(list))
local nextword = list[r]
if nextword == NOWORD then return end
io.write(nextword, " ")
w1 = w2; w2 = nextword
end
---------------------马尔可夫链算法---------------
--]]


-- ---------------------Lua 数据结构  测试---------------
-- -----------Line292 有数组,队列,列表的测试-----------------
-- -----------io.lines() 效率明显低于 io.read("*all") --------------------
-- print("数组的插入和移除要注意")
-- local t = {1,2,3,3,5,3,6}
-- -- ------错误,第四个 3 没有被移除,ipairs 内部会维护一个变量记录遍历的位置,remove 掉第三个数字 3 之后,ipairs 下一个返回的值是 5 而不是 3 
-- -- for i, v in ipairs(t) do
-- -- if v == 3 then
-- -- table.remove(t, i)
-- -- end
-- -- end
-- -- ------错误,第四个 3 没有被移除,ipairs 内部会维护一个变量记录遍历的位置,remove 掉第三个数字 3 之后,ipairs 下一个返回的值是 5 而不是 3 
-- -- ------错误,i=i-1 这段代码没有用,i 的值始终是从 1 到 #t,for 循环里修改 i 的值不起作用 
-- -- for i = 1, #t do 
-- -- if t[i] == 3 then
-- -- table.remove(t, i)
-- -- i = i - 1
-- -- end
-- -- end
-- -- ------错误,i=i-1 这段代码没有用,i 的值始终是从 1 到 #t,for 循环里修改 i 的值不起作用 
-- -- ------ 正确,从后往前遍历 
-- -- for i = #t, 1, -1 do
-- -- if t[i] == 3 then
-- -- table.remove(t, i)
-- -- end
-- -- end
-- -- ------ 正确,从后往前遍历删除,Lua table整理是往前移动
-- -- ------ 正确,自己控制 i 的值是否增加 
-- -- local i = 1
-- -- while t[i] do
-- -- if t[i] == 3 then
-- -- table.remove(t, i)
-- -- else
-- -- i = i + 1
-- -- end
-- -- end
-- -- ------ 正确,自己控制 i 的值是否增加 
-- -- for i, v in ipairs(t) do
-- -- print(i, v)
-- -- end
-- ---------------数组的插入和移除要注意--------------------
-- ---------------lua 中的每个字符串都是单独的一个拷贝,拼接两个字符串会产生一个新的拷贝,如果拼接操作特别多,就会影响性能--------------------
-- ---------------concat 可以将 table 的数组部分拼接成一个字符串,中间用 seq 分隔-----------------------------
-- -- local beginTime = os.clock()
-- -- local str = ""
-- -- for i = 1,30000 do
-- -- str = str..i
-- -- end
-- -- local endTime = os.clock()
-- -- print(endTime - beginTime) ------ 消耗 0.7 秒,产生了 30000 个字符串拷贝,但只有最后一个是有用的
-- -- local beginTime = os.clock()
-- -- local t = {}
-- -- for i = 1,30000 do
-- -- t[i] = i
-- -- end
-- -- local str = table.concat(t, " ")
-- -- local endTime = os.clock()
-- -- print(endTime - beginTime)------ 消耗 0.027 秒,利用 concat,一次性把字符串拼接出来,只产生了一个字符串拷贝 
-- ---------------lua 中的每个字符串都是单独的一个拷贝,拼接两个字符串会产生一个新的拷贝,如果拼接操作特别多,就会影响性能--------------------
-- --------------- Lua中对table排序实例 --------------------
-- ---------- 值排序 之 数组模式 -----------------
-- -- local test0 ={1,9,2,8,3,7,4,6}
-- -- table.sort(test0)  --从小到大排序
-- -- for i,v in pairs(test0) do
   -- -- io.write(v.." ")
-- -- end
-- -- print("");
-- -- table.sort(test0, function (a, b) return a > b end) --从大到小排序
-- -- for i,v in pairs(test0) do
   -- -- io.write(v.." ")
-- -- end
-- -- print(" ")
-- ---------- 值排序 之 数组模式 -----------------
-- ---------- 值排序 之 表单模式 -----------------
-- -- local test2 = {
-- -- {id=1, name="zhao"},
-- -- {id=9, name="qian"},
-- -- {id=2, name="sun"},
-- -- {id=8, name="li"},
-- -- {id=5, name="zhou"},
-- -- }
-- -- table.sort(test2, function(a, b) return a.id < b.id end)
-- -- for i in pairs(test2) do
   -- -- print(test2[i].id, test2[i].name)
-- -- end
-- ---------- 值排序 之 表单模式 -----------------
-- ---------- 键值排序 -----------------
-- local test1 = {a = 1, f = 9, d = 2, c = 8, b = 5}
-- local key_test = {}
-- local val_test = {}
-- local newKeyTest1 = {}
-- local newValTest1 = {}
-- local newTest1ValKey = {}
-- local newTest1 = {}
-- -- table.sort(test1, function (a, b) return a > b end) ---- 排序都是value值, 这样是不能排序
-- for i in pairs(test1) do
-- print('test1', i, test1[i])
-- table.insert(key_test, i)
-- table.insert(val_test, test1[i])
-- -- table.insert(newTest1ValKey, test1[i].. '='.. i) -----新表的下标是数字, 后边是个字符串
-- newTest1ValKey[test1[i]] = i -----新表的下标是自定义的填充
-- end
-- -- table.sort(newTest1ValKey, function (a, b) return a > b end) ---- 排序都是value值, 这样是不能排序
-- -- for i in pairs(newTest1ValKey) do
   -- -- print('newTest1ValKey', i, newTest1ValKey[i])
-- -- end
-- -- -- print("count: ", #key_test, #val_test)
-- -- table.sort(key_test) ---- a, b, c, d, f
-- -- for i,v in pairs(key_test) do
-- -- print('key_test', i, v)
    -- -- table.insert(newKeyTest1, v)
-- -- end
-- table.sort(val_test) ---- 1, 2, 5, 8, 9
-- for i,v in pairs(val_test) do
-- print('val_test', i, v)
-- newTest1[v] = newTest1ValKey[v]
-- end
-- -- -- -- -- --print("count: ",#newKeyTest1, #newValTest1)
-- -- -- -- -- table.sort(newValTest1, function (a, b) return a < b end) -----除非是数组小标的table,否则都是hash排列的无序的table,要使用有序,必须sort
-- -- -- -- -- for i, v in pairs(newValTest1) do
-- -- -- -- -- print('newValTest1', i, v)
-- -- -- -- -- --table.insert(newTest1, newTest1ValKey[v]..'='.. v) -----新表的下标是数字, 后边是个字符串
-- -- -- -- -- newTest1[v] = newTest1ValKey[v]
-- -- -- -- -- end
-- table.sort(newTest1, function (a, b) return a < b end) -----除非是数组小标的table,否则都是hash排列的无序的table,要使用有序,必须sort
-- for i,v in pairs(newTest1) do
-- print("reversal_test1_newTest1", i, v) ----好像反转后的newTest1没有正确排序
-- end


-- ---------- 键值排序 -----------------
-- --------------- Lua中对table排序实例 --------------------
-- ---------------------Lua 数据结构  测试---------------

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值