如何理解lua中的表格?

时间:2019-11-08 11:44:59

标签: lua

    > polyline = {color = "blue", thickness = 2, npoints = 4, {x=0,y=0}, {x=-10,y=0}, {x=-10,y=1}, {x=0,y=1}}
    > print(polyline[2])
    table: 0x55ad5c0f3f90
    > print(polyline[2].x)
-10

为什么print(polyline [2])给出-10?

1 个答案:

答案 0 :(得分:2)

如果您未明确提供键,则会将表元素分配给表构造函数中的数字键。

polyline = {color = "blue", thickness = 2, npoints = 4, {x=0,y=0}, {x=-10,y=0}, {x=-10,y=1}, {x=0,y=1}}

等同于

do
  polyline = {}
  polyline.color = "blue"
  polyline.thickness = 2
  polyline.npoints = 4
  do
    polyline[1] = {}
    polyline[1].x = 0
    polyline[1].y = 0
  end
  do
    polyline[2] = {}
    polyline[2].x = -10
    polyline[2].y = 0
  end
  do
    polyline[3] = {}
    polyline[3].x = -10
    polyline[3].y = 1
  end
  do
    polyline[4] = {}
    polyline[4].x = 0
    polyline[4].y = 1
  end
end

参考

https://www.lua.org/manual/5.3/manual.html#3.4.9