之后添加值以键入 table lua

add value afterwards to key in table lua

有人知道如何向已有值的键添加值吗?

例如:

x = {}
x[1] = {string = "hallo"}
x[1] = {number = 10}

print(x[1].string) --nil
print(x[1].number) --10

这两个东西应该都可以打印出来。同样的方式在这里是可能的:

x[1] = { string = "hallo" ; number = 10} 

之后我只需要在 table 中添加一些信息,尤其是在同一个键中。 谢谢!

x = {}  -- create an empty table
x[1] = {string = "hallo"} -- assign a table with 1 element to x[1]
x[1] = {number = 10} -- assign another table to x[1]

第二个赋值覆盖第一个赋值。

x[1]["number"] = 10 或简写 x[1].number = 10 将在 table x[1]

中添加值为 10 的字段 number

请注意,您的 x[1] = { string = "hallo" ; number = 10} 实际上等同于

x[1] = {}
x[1]["string"] = "hallo"
x[1]["number"] = 10