首页 > 解决方案 > 之后添加值以键入表 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} 

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

标签: lualua-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或 short将向表中x[1].number = 10添加一个number具有值的字段10x[1]

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

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

推荐阅读