LUA笔记之表

表据说是LUA的核, 呵呵, 看例子吧, 看上去, 跟java的list很像, 又有点像json:

    a = {}     -- create a table and store its reference in `a'
    k = "x"
    a[k] = 10        -- new entry, with key="x" and value=10
    a[20] = "great"  -- new entry, with key=20 and value="great"
    print(a["x"])    --> 10
    k = 20
    print(a[k])      --> "great"
    a["x"] = a["x"] + 1     -- increments entry "x"
    print(a["x"])    --> 11

这货好混乱, 像list又完全不理数据类型的赶脚.

为了内存好, 用完就自动回收吧.

    a = {}
    a["x"] = 10
    b = a      -- `b' refers to the same table as `a'
    print(b["x"])  --> 10
    b["x"] = 20
    print(a["x"])  --> 20
    a = nil    -- now only `b' still refers to the table
    b = nil    -- now there are no references left to the table

至于为什么这玩意儿称之为表(table), 看下面这个例子:

    a = {}     -- empty table
    -- create 1000 new entries
    for i=1,1000 do a[i] = i*2 end
    print(a[9])    --> 18
    a["x"] = 10
    print(a["x"])  --> 10
    print(a["y"])  --> nil

看到了吧, 可以直接用"x"来给a这个表的某个元素赋值, 看上去像不像java里面的map? 我直接呵呵.

    a.x = 10                    -- same as a["x"] = 10
    print(a.x)                  -- same as print(a["x"])
    print(a.y)                  -- same as print(a["y"])

这个东西看起来又像js里面的属性啊.奇妙~~~~

    a = {}
    x = "y"
    a[x] = 10                 -- put 10 in field "y"
    print(a[x])   --> 10      -- value of field "y"
    print(a.x)    --> nil     -- value of field "x" (undefined)
    print(a.y)    --> 10      -- value of field "y

上面例子说明, x跟"x"不是一码事儿, "x", 感觉像一个map里面的key, 而x则类似于array里面的脚标.

其实, 全部理解成map就对了, map跟table, 本质上区别不大, 都是key跟value的关系, 只是key的值可以是数字, 也可以是string, 这么理解就清晰了.

嗯, 官方也说了, 如果真的需要一个array, 就把key挨个做成数字即可:

    -- read 10 lines storing them in a table
    a = {}
    for i=1,10 do
      a[i] = io.read()
    end

因为{}这玩意儿给了table, 搞得LUA里面的过程跟循环都用do跟end关键字来当界定符.

用下面这个例子结束这一篇:

    -- print the lines
    for i,line in ipairs(a) do
      print(line)
    end

ipairs()是一个函数, 能枚举a里面的所有元素.

另外一个值得注意的地方是, LUA推荐使用1当数组的第一个元素, 而不是0, 这跟几乎所有的语言背道而驰了...

原文地址:https://www.cnblogs.com/Montauk/p/5457941.html