【问题标题】:add value afterwards to key in table lua之后添加值以键入表 lua
【发布时间】:2021-12-17 03:03:13
【问题描述】:

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

例如:

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} 

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

【问题讨论】:

    标签: lua lua-table


    【解决方案1】:
    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 将在表 x[1] 中添加一个值为 10 的字段 number

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

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

    【讨论】:

      猜你喜欢
      • 2021-12-20
      • 2021-12-16
      • 2017-08-22
      • 1970-01-01
      • 2015-04-19
      • 2017-05-15
      • 1970-01-01
      • 2017-09-13
      • 1970-01-01
      相关资源
      最近更新 更多