发布于 2016-01-23 09:28:05 | 192 次阅读 | 评论: 0 | 来源: 网友投递

这里有新鲜出炉的Lua教程,程序狗速度看过来!

Lua 脚本语言

Lua 是一个小巧的脚本语言。是巴西里约热内卢天主教大学(Pontifical Catholic University of Rio de Janeiro)里的一个研究小组,由Roberto Ierusalimschy、Waldemar Celes 和 Luiz Henrique de Figueiredo所组成并于1993年开发。 其设计目的是为了嵌入应用程序中,从而为应用程序提供灵活的扩展和定制功能。Lua由标准C编写而成,几乎在所有操作系统和平台上都可以编译,运行。Lua并没有提供强大的库,这是由它的定位决定的。所以Lua不适合作为开发独立应用程序的语言。Lua 有一个同时进行的GIT项目,提供在特定平台上的即时编译功能。


这篇文章主要介绍了Lua 中 pairs 和 ipairs 的区别,本文用官方文档和代码实例总结了它的们的区别,需要的朋友可以参考下

官方文档上的说明:

ipairs (t)

Returns three values: an iterator function, the table t, and 0, so that the construction

for i,v in ipairs(t) do body end

will iterate over the pairs (1,t[1]), (2,t[2]), ···, up to the first integer key absent from the table.

pairs (t)

Returns three values: the next function, the table t, and nil, so that the construction

for k,v in pairs(t) do body end

will iterate over all key–value pairs of table t.

See function next for the caveats of modifying the table during its traversal.

这样就可以看出 ipairs以及pairs 的不同。pairs可以遍历表中所有的key,并且除了迭代器本身以及遍历表本身还可以返回nil;但是ipairs则不能返回nil,只能返回数字0,如果遇到nil则退出。它只能遍历到表中出现的第一个不是整数的key

下面举个例子


local tabFiles = {   
[3] = "test2",   
[6] = "test3",   
[4] = "test1"  
}   
for k, v in ipairs(tabFiles) do  
    print(k, v)   
end  

猜测它的输出结果是什么呢?根据刚才的分析,它在 ipairs(tabFiles) 遍历中,当key=1时候value就是nil,所以直接跳出循环不输出任何值。


>lua -e "io.stdout:setvbuf 'no'" "test.lua"  
>Exit code: 0  

那么,如果是


for k, v in pairs(tabFiles) do  
    print(k, v)   
end  

则会输出所有:


>lua -e "io.stdout:setvbuf 'no'" "test.lua"    
3 test2   
6 test3   
4 test1   
>Exit code: 0  

现在改变一下表内容:


local tabFiles = {   
[1] = "test1",   
[6] = "test2",   
[4] = "test3"  
}   
  
for k, v in ipairs(tabFiles) do  
    print(k, v)   
end  

现在的输出结果显而易见就是key=1时的value值test1


>lua -e "io.stdout:setvbuf 'no'" "test.lua"    
1 test1   
>Exit code: 0  


-- [[示例1.]] --   
local tt =   
{   
    [1] = "test3",   
    [4] = "test4",   
    [5] = "test5"  
}   
  
for i,v in pairs(tt) do     -- 输出 "test4" "test3" "test5"  
    print( tt[i] )   
end   
  
for i,v in ipairs(tt) do    -- 输出 "test3" k=2时断开   
    print( tt[i] )   
end   
  
-- [[示例2.]] --   
tbl = {"alpha", "beta", [3] = "uno", ["two"] = "dos"}   
  
for i,v in ipairs(tbl) do    --输出前三个   
    print( tbl[i] )   
end   
  
for i,v in pairs(tbl) do    --全部输出   
    print( tbl[i] )   
end  



最新网友评论  共有(0)条评论 发布评论 返回顶部

Copyright © 2007-2017 PHPERZ.COM All Rights Reserved   冀ICP备14009818号  版权声明  广告服务