---
title: "lua学习： lua的table类型"
author: "rstevens"
date: "2011-09-07T15:07:13Z"
tags: ["Lua"]
categories: ["编程语言"]
slug: "lua-lua-table"
draft: false
lastmod: "2011-09-07T15:10:47Z"
id: 1167642
url: "https://rstevens.iteye.com/blog/1167642"
---

1、 table 是 lua 中最重要的数据类型。
2、 table 类似于 python 中的字典。
3、 table 只能通过构造式来创建

例1：

```lua

mytable = { a = 10, b = 11, c = 20, ddd = 30 }
print(mytable["a"])

```



注释： 
1）、 table 中的每项要求是 key = value 的形式
2）、 key 只能是字符串， 这里的 a, b, c, ddd 都是字符串，但是不能加上引号 
3）、 通过 key 来访问 table 的值，这时候， a 必须加上引号

例2：


```lua

mytable = { 10, ddd = 30, 12, 13 }

print(mytable[1])
print(mytable[2])
print(mytable[3])


```


注释：
1）、 table 中可以出现没有 key 的项，这个时候，lua 会把这个 table 当做一个数组来看待，这个项的key就是它在数组中的下标（从1开始）
2）、 上例中， mytable 是 10， mytable 是 12， ddd = 30 这项会被跳过。mytable 是 13


综上，可以发现， <span style="color:red">table 是一个数组和字典的混合体。</span>