码迷,mamicode.com
首页 > 其他好文 > 详细

lua table 初识

时间:2015-04-30 13:59:26      阅读:120      评论:0      收藏:0      [点我收藏+]

标签:

 
 1 local demo = {"demoValue"}
 2 local function fun()
 3   print"hello world"
 4 end
 5 local tableDemo = { 
 6             ["a3132t"] = "valide?",
 7                     [9] = fun,
 8                     [fun] = "a funciton.",
 9                     ["demo"] = "anoter string",
10                     demo = "a string",            --Syntactic sugar
11                     ["demo"] = "come on",
12                     "here to be count!",
13                     [demo] = "a table demo to be anoter table‘s key", 
14                     [1]="demo", 
15                     "world" ,
16                     "apple", 
17                     "helloworld",
18                 }

1.table中所有的元素都以逗号分隔;

2.table中所有的元素都要添加索引——以中括号"["和"]" 括起来;
  2.1.如果不使用中括号,合法的元素会以数字为索引,且按顺序自动从加1往后递增;
  2.2.如果没有使用"["和"]" 括起来,且合法,则认为是字符串索引(Syntactic sugar);

值得注意的是保存着table和function的变量既可以做索引也可以做值。只不过做索引的依然需要遵循以上规则。
以table demo为例,如果没有使用"["和"]" 括起来,那么tableDemo则认为demo只是一个tableDemo元素的key,它实质上字符串"demo"。

1 for k,v in pairs(tableDemo) do
2   print(k,v)
3 end

 

标准输出如下:

 1 1 here to be count!
 2 2    world
 3 3    apple
 4 4    helloworld
 5 5    function: 0x172c730
 6 9    function: 0x172c700
 7 a3132t    valide?
 8 table: 0x172cde0    a table demo to be anoter tables key
 9 demo    come on
10 function: 0x172c700    a funciton.
11 [Finished in 0.0s]

 

 

待续的主题还有:

1.标准库函数如

1 table.sort (table [, comp]),
2 table.insert (table, [pos,] value)
3 table.concat (table [, sep [, i [, j]]])
4 table.remove (table [, pos])

 

2.标准库字符串操作函数

 

lua table 初识

标签:

原文地址:http://www.cnblogs.com/dotdog/p/4468643.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!