自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

通過例子學(xué)習(xí)Lua(3)—Lua數(shù)據(jù)結(jié)構(gòu)

開發(fā) 前端
Lua語言只有一種基本數(shù)據(jù)結(jié)構(gòu), 那就是table, 所有其他數(shù)據(jù)結(jié)構(gòu)如數(shù)組啦、類, 都可以由table實(shí)現(xiàn).

1.簡介

Lua語言只有一種基本數(shù)據(jù)結(jié)構(gòu), 那就是table, 所有其他數(shù)據(jù)結(jié)構(gòu)如數(shù)組啦、類, 都可以由table實(shí)現(xiàn).

2.table的下標(biāo)

例e05.lua

  1. -- Arrays 
  2. myData = {} 
  3. myData[0] = “foo” 
  4. myData[1] = 42 
  5. -- Hash tables 
  6. myData[“bar”] = “baz” 
  7. -- Iterate through the 
  8. -- structure 
  9. for key, value in myData do 
  10. print(key .. “=“ .. value) end 

輸出結(jié)果

0=foo

1=42

bar=baz

程序說明

首先定義了一個(gè)table myData={}, 然后用數(shù)字作為下標(biāo)賦了兩個(gè)值給它. 這種定義方法類似于C中的數(shù)組, 但與數(shù)組不同的是, 每個(gè)數(shù)組元素不需要為相同類型,就像本例中一個(gè)為整型, 一個(gè)為字符串.

程序第二部分, 以字符串做為下標(biāo), 又向table內(nèi)增加了一個(gè)元素. 這種table非常像STL里面的map. table下標(biāo)可以為Lua所支持的任意基本類型, 除了nil值以外.

Lua對(duì)Table占用內(nèi)存的處理是自動(dòng)的, 如下面這段代碼

  1. a = {} 
  2. a["x"] = 10 
  3. b = a -- `b' refers to the same table as `a' 
  4. print(b["x"]) --> 10 
  5. b["x"] = 20 
  6. print(a["x"]) --> 20 
  7. a = nil -- now only `b' still refers to the table 
  8.  
  9. b = nil -- now there are no references left to the table 

b和a都指向相同的table, 只占用一塊內(nèi)存, 當(dāng)執(zhí)行到a = nil時(shí), b仍然指向table,

而當(dāng)執(zhí)行到b=nil時(shí), 因?yàn)闆]有指向table的變量了, 所以Lua會(huì)自動(dòng)釋放table所占內(nèi)存

3.Table的嵌套

Table的使用還可以嵌套,如下例

例e06.lua

  1. -- Table ‘constructor’ 
  2. myPolygon = { 
  3. color=“blue”, 
  4. thickness=2
  5. npoints=4
  6. {x=0y=0}, 
  7. {x=-10, y=0}, 
  8. {x=-5, y=4}, 
  9. {x=0y=4
  10. -- Print the color 
  11. print(myPolygon[“color”]) 
  12. -- Print it again using dot 
  13. -- notation 
  14. print(myPolygon.color) 
  15. -- The points are accessible 
  16. -- in myPolygon[1] to myPolygon[4] 
  17. -- Print the second point’s x 
  18. -- coordinate 
  19. print(myPolygon[2].x) 

程序說明

首先建立一個(gè)table, 與上一例不同的是,在table的constructor里面有{x=0,y=0},這是什么意思呢? 這其實(shí)就是一個(gè)小table, 定義在了大table之內(nèi), 小table的table名省略了。

最后一行myPolygon[2].x,就是大table里面小table的訪問方式。

原文鏈接:http://tech.it168.com/j/2008-02-14/200802141314299.shtml

責(zé)任編輯:陳四芳 來源: 來自ITPUB論壇
相關(guān)推薦

2013-12-13 15:48:52

Lua腳本語言

2013-12-13 16:46:18

Lua腳本語言

2013-12-12 17:30:03

Lua例子

2013-12-13 16:53:00

Lua腳本語言C++

2013-12-13 15:54:32

Lua腳本語言

2011-08-23 16:59:16

C++LUA腳本LUA API

2021-01-12 06:42:50

Lua腳本語言編程語言

2011-08-23 11:13:56

Lua

2011-08-23 13:27:46

Luaglobal變量

2011-08-24 14:14:13

LUA環(huán)境 配置

2011-08-24 11:03:33

LUA環(huán)境 安裝

2011-08-23 15:34:56

Lua模式 匹配

2011-08-23 16:37:05

Lua數(shù)學(xué)庫

2011-08-24 15:42:38

LUA源代碼

2011-08-23 17:33:08

LuaMetatable

2011-08-25 15:41:42

Lua源碼

2011-08-31 15:59:10

LUAWeb 開發(fā)

2011-08-23 10:29:13

LuaPlayer

2011-08-24 15:22:09

2011-08-24 15:34:44

MinGWLua環(huán)境配置
點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號(hào)