days = {"Sunday", "Monday", "Tuesday", "Wednesday",
"Thursday", "Friday", "Saturday"}

will initialize days[1] with the string "Sunday" (the first element has always index 1, not 0), days[2] with "Monday", and so on:

    print(days[4])  --> Wednesday table从1开始,不是从0开始
还有一点,访问不存在的index不会报错,只是返回nil。

Constructors do not need to use only constant expressions. We can use any kind of expression for the value of each element. For instance, we can build a short sine table as

    tab = {sin(1), sin(2), sin(3), sin(4),
sin(5), sin(6), sin(7), sin(8)}

To initialize a table to be used as a record, Lua offers the following syntax: table作为record使用

    a = {x=0, y=0}

which is equivalent to

    a = {}; a.x=0; a.y=0

No matter what constructor we use to create a table, we can always add and remove other fields of any type to it:

    w = {x=0, y=0, label="console"}
x = {sin(0), sin(1), sin(2)}
w[1] = "another field"
x.f = w
print(w["x"]) --> 0
print(w[1]) --> another field
print(x.f[1]) --> another field
w.x = nil -- remove field "x" That is, all tables are created equal; constructors only affect their initialization.

Every time Lua evaluates a constructor, it creates and initializes a new table. Consequently, we can use tables to implement linked lists:

每次执行一个构造函数,lua创建和初始化一个新的table,因此,你可以使用table来实现linked list.

    list = nil
for line in io.lines() do
list = {next=list, value=line}
end
This code reads lines from the standard input and stores them in a linked list, in reverse order. Each node in the list is a table with two fields: value, with the line contents, and next, with a reference to the next node. The following code prints the list contents:
    l = list
while l do
print(l.value)
l = l.next
end
(Because we implemented our list as a stack, the lines will be printed in reverse order.) Although instructive, we hardly use the above implementation in real Lua programs; lists are better implemented as arrays, as we will see in Chapter 11.

We can mix record-style and list-style initializations in the same constructor:

我们可以混合记录性风格和列表形风格来初始化。

    polyline = {color="blue", thickness=2, npoints=4,
{x=0, y=0},
{x=-10, y=0},
{x=-10, y=1},
{x=0, y=1}
}
The above example also illustrates how we can nest constructors to represent more complex data structures. Each of the elements polyline[1], ..., polyline[4] is a table representing a record:
这里例子也展示了可以嵌套构造函数来表示复杂的结构。
    print(polyline[2].x)    --> -10 

Those two constructor forms have their limitations. For instance, you cannot initialize fields with negative indices, or with string indices that are not proper identifiers. For such needs, there is another, more general, format. In this format, we explicitly write the index to be initialized as an expression, between square brackets: 用[exp]表示索引

    opnames = {["+"] = "add", ["-"] = "sub",
["*"] = "mul", ["/"] = "div"} i = 20; s = "-"
a = {[i+0] = s, [i+1] = s..s, [i+2] = s..s..s} print(opnames[s]) --> sub
print(a[22]) --> ---
That syntax is more cumbersome, but more flexible too: Both the list-style and the record-style forms are special cases of this more general one. The constructor 这个语法更笨重,但是比较灵活。list-style和record-style是这种一般化形式的特例。
    {x=0, y=0}
is equivalent to
    {["x"]=0, ["y"]=0}
and the constructor
    {"red", "green", "blue"}
is equivalent to
    {[1]="red", [2]="green", [3]="blue"}

For those that really want their arrays starting at 0, it is not difficult to write the following:

想要index从0开始,把第一个设置为0,这并不影响其他的,第二个默认为1,因为它是构造函数中的第一个list类型,其他的值跟随他。
 days = {[0]="Sunday", "Monday", "Tuesday", "Wednesday",
"Thursday", "Friday", "Saturday"}
Now, the first value, "Sunday", is at index 0. That zero does not affect the other fields, but "Monday" naturally goes to index 1, because it is the first list value in the constructor; the other values follow it. Despite this facility, I do not recommend the use of arrays starting at 0 in Lua. Remember that most functions assume that arrays start at index 1, and therefore will not handle such arrays correctly. 

不推荐在Lua最开始位置为0,因为大多数函数式是从1开始的。

You can always put a comma after the last entry. These trailing commas are optional, but are always valid:

    a = {[1]="red", [2]="green", [3]="blue",} 同php一样,table后面放分号不影响正确性。
Such flexibility makes it easier to write programs that generate Lua tables, because they do not need to handle the last element as a special case。

Finally, you can always use a semicolon instead of a comma in a constructor. We usually reserve semicolons to delimit different sections in a constructor, for instance to separate its list part from its record part:

    {x=10, y=45; "one", "two", "three"}
最后,你可以使用分号代替逗号,我们通常保留分号来区分不同的段。 删除table
赋值为nil即可。
lua table作为array:

Tables as arrays

First, remember that tables are still just key/value containers, Lua doesn't actually have an array type. But tables can be treated like arrays, which is explained here:

Table constructors can contain a comma separated list of objects to create an "array":

> t = {"a", "b", "c"}
> = t[1]
a
> = t[3]
c
This is a syntax shortcut for:
> t = {[1]="a", [2]="b", [3]="c"}
> = t[1]
a
> = t[3]
c
So it's still just a key/value association.

You can also mix the array syntax with the usual key=value syntax:

> t = {"a", "b", [123]="foo", "c", name="bar", "d", "e"}
> for k,v in pairs(t) do print(k,v) end
1 a
2 b
3 c
4 d
5 e
123 foo
name bar
求array length,
> t = {"a", "b", "c"}
> = #t
3

The # operator doesn't count all the items in the table (!), instead it finds the last integer (not-fractional number) key. Because of how it's implemented, its results are undefined if all the integer keys in the table aren't consecutive (that is, don't use it for tables used as sparse arrays[2]).

> a={}
> a[1000]=1
> print(#a)

输出0.

请记住对于所有未初始化的元素的索引结果都是nil。Lua将nil作为定界数组结尾的标志。当一个数组有
“空隙hole”是,即中间含有nil时,长度操作符会认为这些nil元素就是结尾标志,因此应该避免对于那些
含有“空隙”的数组使用#。大多数数组不会包含“空隙”,因此,#一般是安全的。
如果真的需要处理那些含有“空隙”的数组,使用使用table.maxn.他将返回一个table的最大正index。

print(table.maxn(a)) ->1000

There are two ways to add an item to the end of an array:

> t = {}
> table.insert(t, 123)
> t[#t+1] = 456
> = t[1]
123
> = t[2]
456

table.insert takes an optional index parameter to insert into the middle of an array. It shifts up any other integer keys above the index:

> t = {"a", "c"}
> table.insert(t, 2, "b")
> = t[1], t[2], t[3]
a b c

table.remove removes an item from an array, shifting down any remaining integer keys:

> t = {"a", "b", "c"}
> table.remove(t, 2)
> = t[1], t[2]
a c

To loop over an array, use ipairs. Unlike pairs, it only gives you the consecutive integer keys from 1, and it guarantees their order. With pairs, the number keys will not necessarily be given in the correct order!

> t = {"a", "b", "c"}
> for i, v in ipairs(t) do print(i, v) end
1 a
2 b
3 c

To join together an array of strings, there's table.concat. It takes optional separator, start, and end parameters. Here we only use the separator:

> t = {"a", "b", "c"}
> = table.concat(t, ";")
a;b;c

For a list of all the table.* functions and their complete documentation, see [[3]].


Table values are references

Unlike basic types such as numbers, when you store a table in a new variable, pass it to a function, etc., you don't create a new copy of the table. Instead you get a new reference (think of it like a handle, or pointer) to the same table: table值是引用.

> t = {}
> u = t
> u.foo = "bar"
> = t.foo
bar
> function f(x) x[1] = 2 end
> f(t)
> = u[1]
2

Tables are freed from memory by the garbage collector sometime after the last reference to them is gone (not necessarily instantly). The garbage collector is designed to work correctly even in the case where a table (directly or indirectly) contains a reference to itself.

A related thing to remember is that table comparison works by reference. Comparing tables using == will return false even if the two tables have the same contents, they must actually be references to the same table.

Finally, if you want to copy a table, you'll have to do it manually. Lua offers no standard function for it, mainly because of all the different ways you can copy a table.

Tables as unordered sets

Often people new to Lua will create an array to store a group of objects, even if the order isn't necessary. The problem with this is that removal is slow (need to shift down other items), and checking if an item is in the array is slow (need to loop over all the items).

This can be solved by storing items in the keys and setting values to a dummy value (like true), so you can use a table like an unordered set with fast insertion, removal, and lookup.

The main differences are that there's no easy way to get the count (you have to use a loop), and you can't store the same item twice in the set.

So if you need to store a group of items, it's best to consider both sets and arrays to see what fits your situation best.

local items = {}

-- add some items to the set
items["foo"] = true
items[123] = true -- is "foo" in the set?
if items["foo"] then
-- do stuff
end -- remove item from the set
items[123] = nil

参考:http://www.lua.org/pil/3.6.html

 http://lua-users.org/wiki/TablesTutorial
												





											

Lua table使用的更多相关文章

  1. lua table integer index 特性

    table.maxn (table) Returns the largest positive numerical index of the given table, or zero if the t ...

  2. 树形打印lua table表

    为方便调试lua程序,往往想以树的形式打印出一个table,以观其表内数据.以下罗列了三种种关于树形打印lua table的方法;法一 local print = print local tconca ...

  3. lua table 排序--满足多条件排序

    前提 假设 一个小怪 有三种属性,等级(level).品质(quality).id(pid) 我们需要对他们进行排序,两种排序情况,第一是单一属性排序,比如按照等级进行排序,或者多种属性进行优先级排序 ...

  4. cocos2d-x lua table数据存储

    cocos2d-x lua table数据存储 version: cocos2d-x 3.6 1. 将table转为json http://blog.csdn.net/songcf_faith/art ...

  5. cocos2d-x lua table与json的转换

    cocos2d-x lua table与json的转换 version: cocos2d-x 3.6 1.引入json库 require("src/cocos/cocos2d/json&qu ...

  6. lua table表

    lua table表 语法结构 创建一个 table 直接使用 "{}" 即可 table1 = {} -- 赋值 table1["name"] = " ...

  7. lua table表判断是否为空

    官方手册里早已经给了答案,那就是靠lua内置的next函数 即如此用: a = {} if next(a) == nil then next其实就是pairs遍历table时用来取下一个内容的函数. ...

  8. 关于 lua table表存储函数且运用

    --table 是lua的一种数据结构用来帮助我们创建不同的数据类型.如:数组和字典--lua table 使用关联型数组,你可以用任意类型的值来做数组的索引,但这个值不能是nil--lua tabl ...

  9. lua table排序报错与解决

    lua table排序 table的sort函数 比如按照大小进行排序,下面这种写法在某些情况下可能会排序错误,甚至报invalid order function for sorting table. ...

随机推荐

  1. PHP简单 对象(object) 与 数组(array) 的转换

    数组是PHP的灵魂,非常强大,但有时候面向对象编程也是挺方便的,数组 与 对象 之间切换也是常有的事: /** * 数组 转 对象 * * @param array $arr 数组 * @return ...

  2. Jquery中$.load(),$.get(),$.post(),$.ajax(),$.getJSON()的作用与不同

    这个五个都是获取页面或者数据的方法.. 都是基于Ajax协议的..   $.get(url,[data],[callback])     //描述: 从服务器加载数据,请求方式为GET.  url   ...

  3. 数的长度---nyoj69

    超时 #include <stdio.h>#include <string.h>#define M 1000001int shu[M]; int main(){ int n, ...

  4. PHP 开发中的外围资源性能分析(二)

    暂且不讨论「PHP 是不是最好的编程语言」,本文我们将分别分析一下在 PHP 程序的后端外围资源和前端外围资源,它们对整个 PHP Web 应用体验的影响,这往往比语言本身大得多. 上一篇中我们分析了 ...

  5. mysql distinct跟group by性能

    mysql distinct和group by性能   1,测试前的准备 //准备一张测试表 mysql> CREATE TABLE `test_test` ( ->   `id` int ...

  6. c语言太easy笔误的,这将做

    调试发现时间写的一样NB代码 test.c int add(string); int main() { char* p = "11222"; add(p); return 0; } ...

  7. 国内apk加固的破解方法

    国内apk加固的破解方法 By Bob Pan 国内的apk加固技术都使用了将原有的dex隐藏, 在运行时解压, 并且通过修改app的类加载器的方式实现加固. 参考: AndoridAPK反逆向解决方 ...

  8. 201521123004《Java程序设计》第6周学习总结

    1. 本周学习总结 1.1 面向对象学习暂告一段落,请使用思维导图,以封装.继承.多态为核心概念画一张思维导图,对面向对象思想进行一个总结. 注1:关键词与内容不求多,但概念之间的联系要清晰,内容覆盖 ...

  9. 虚拟DOM详解

    虚拟DOM简介 Virtual Dom可以看做一棵模拟了DOM树的JavaScript对象树,其主要是通过vnode,实现一个无状态的组件,当组件状态发生更新时,然后触发Virtual Dom数据的变 ...

  10. LeetCode 695 岛屿的最大面积

    题目: 给定一个包含了一些 0 和 1的非空二维数组 grid , 一个 岛屿 是由四个方向 (水平或垂直) 的 1 (代表土地) 构成的组合.你可以假设二维矩阵的四个边缘都被水包围着. 找到给定的二 ...