繁体   English   中英

Lua表如何工作

[英]How Lua tables work

我开始从《 Lua编程》(第2版)中学习Lua,但我对书中的以下内容不了解。 它非常模糊地解释。

a。) w={x=0,y=0,label="console"}

b。) x={math.sin(0),math.sin(1),math.sin(2)}

c。) w[1]="another field"

d。) xf=w

e。) print (w["x"])

f。) print (w[1])

g。) print xf[1]

当我在a。之后执行print(w[1]) )时,为什么不打印x=0

c。)做什么?

e。)和print (wx)什么区别?

b。)和g。)的作用是什么?

您必须意识到这一点:

t = {3, 4, "eggplant"}

与此相同:

t = {}
t[1] = 3
t[2] = 4
t[3] = "eggplant"

而且这个:

t = {x = 0, y = 2}

与此相同:

t = {}
t["x"] = 0
t["y"] = 2

或这个:

t = {}
t.x = 0
t.y = 2

在Lua中,表不仅是列表,而且是关联数组

当您打印w[1] ,真正重要的是c。行。实际上, w[1]直到c。行才被定义。

e。)和print (wx)之间没有区别。

b。)创建一个名为x的新表,该表与w分开。

d。) x放置对w的引用。 (注意:它实际上并没有复制w ,仅是引用 。如果您曾经使用过指针,则类似。)

g。)可以分为两部分。 首先,我们得到xf ,这是由于d行而引用w另一种方法。 然后我们查找该表的第一个元素,由于c行,它是"another field" 。)

还有一种在嵌入式表声明中创建键的方法。

x = {["1st key has spaces!"] = 1}

这样做的好处是您可以使用带空格和任何扩展ASCII字符的键。 实际上,键实际上可以是任何东西,甚至可以是实例对象。

function Example()
    --example function
end
x = {[Example] = "A function."}

任何变量,值或数据都可以放在方括号中作为键。 值也一样。 实际上,这可以代替python中的in关键字之类的功能,因为您可以按值索引表以检查它们是否存在。

在表的未定义部分获取值不会导致错误。 它只会给你零。 使用未定义的变量也是如此。

local w = {
    --[1] = "another field"; -- will be set this value
    --["1"] = nil;  -- not save to this place, different with some other language
    x = 0;
    y = 0;
    label = "console";

}
local x = {
    math.sin(0);
    math.sin(1);
    math.sin(2);
}

w[1] = "another field" -- 
x.f  = w

print (w["x"])

-- because x.f = w
-- x.f and w point one talbe address
-- so value of (x.f)[1] and w[1] and x.f[1] is equal
print (w[1])
print ((x.f)[1])
print (x.f[1])

-- print (x.f)[1] this not follows lua syntax 
-- only a function's has one param and type of is a string
-- you can use print "xxxx"
-- so you print x.f[1] will occuur error


-- in table you can use any lua internal type 's value to be a key
-- just like

local t_key = {v=123}
local f_key = function () print("f123") end

local t = {}
t[t_key] = 1
t[f_key] = 2

-- then t' key actualy like use t_key/f_key 's handle 

-- when you user t[{}] = 123, 
-- value 123 related to this no name table {} 's handle

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM