Data structures 如何在表/元表中添加/删除元素Lua脚本

Data structures 如何在表/元表中添加/删除元素Lua脚本,data-structures,lua,Data Structures,Lua,我知道如何使用初始值创建表/元表,但不知道如何在创建后插入或删除元素。如何使用Lua脚本中的最佳实践来实现这一点?有什么标准函数可以做到这一点吗?这里介绍了从Lua表中插入和删除的各种方法;首先,对于数组样式表: local t = { 1, 2, 3 } -- add an item at the end of the table table.insert(t, "four") t[#t+1] = 5 -- this is faster -- insert an item at posi

我知道如何使用初始值创建表/元表,但不知道如何在创建后插入或删除元素。如何使用Lua脚本中的最佳实践来实现这一点?有什么标准函数可以做到这一点吗?

这里介绍了从Lua表中插入和删除的各种方法;首先,对于数组样式表:

local t = { 1, 2, 3 }

-- add an item at the end of the table
table.insert(t, "four")
t[#t+1] = 5  -- this is faster

-- insert an item at position two, moving subsequent entries up
table.insert(t, 2, "one and a half")

-- replace the item at position two
t[2] = "two"

-- remove the item at position two, moving subsequent entries down
table.remove(t, 2)
local t = { a = 1, b = 2, c = 3 }

-- add an item to the table
t["d"] = 4
t.e = 5

-- remove an item from the table
t.e = nil
对于哈希样式表:

local t = { 1, 2, 3 }

-- add an item at the end of the table
table.insert(t, "four")
t[#t+1] = 5  -- this is faster

-- insert an item at position two, moving subsequent entries up
table.insert(t, 2, "one and a half")

-- replace the item at position two
t[2] = "two"

-- remove the item at position two, moving subsequent entries down
table.remove(t, 2)
local t = { a = 1, b = 2, c = 3 }

-- add an item to the table
t["d"] = 4
t.e = 5

-- remove an item from the table
t.e = nil

很好,但是运算符“#”是什么,它是做什么的?
是长度运算符;默认情况下,它返回数组样式表中的条目数或字符串中的字节数。请注意,它不适用于哈希样式表。@LuizR.P.Santiago:您知道,Lua有非常全面的文档。你们可能想找个时间看看它。你们有并没有费心看一眼手册?你们是对的,很抱歉浪费了你们的时间。