在嵌套的表格中插入元素

我需要知道如何使用table.insert,在一个嵌套在另一个表格中的表格中插入元素。这就是我的代码:

Table = {} --主表格

function InsertNewValues()

local TIME = --任何值,字符串或整数
local SIGNAL = --任何值,字符串或整数
table.insert(Table, {TIME, SIGNAL})

end

这个函数允许我在调用它时插入TIME和SIGNAL的值,所以表格将会是这样的:

Table[1][1] = TIME
Table[1][2] = SINGAL
...
Table[...][1] = TIME
Table[...][2] = SIGNAL

但是 ... 我需要把TIME和SIGNAL的值插入到另一个嵌套在"Table"表格中的表格中,而那个表格作为一个键来引用这些值... TIME和SIGNAL ...

因此,生成的表格如下所示:

+Table
|
+-[1]othertable
|
+-+[1]TIME - [2]SIGNAL
+-+[1]TIME - [2]SIGNAL
+- ...
|
+-[2]othertable
|
+-+[1]TIME - [2]SIGNAL
+-+[1]TIME - [2]SIGNAL
+- ...

我该怎么做才能实现这个功能?

----------------- 编辑 -----------------

我没有讲清楚,我需要的是:

给定一个名为"Table"的表格,我需要能够在该表格中使用"字符串"作为"键"。这将是:

-- 我的"容器"表格的名称
Table = {}

要插入的值

Time = '1秒' -- 这个值可以根据需要更改
Value = '逻辑' -- 这个值可以根据需要更改

使用字符串键"RandomName"添加到我的主表格"Table"中

-- "RandomName"可以根据需要更改

function AddNewValues ()
   table.insert (Table [RandomName], {Time, Value})
end

每次调用函数"AddNewValues()"时,它都应将"Time"和"Value"中存在的值作为"NEW ENTRY"添加到该"RandomName"中。

因此,表格的结果可能如下所示:

+table -- 包含
+-RandomName-- 用于访问的字符串键
+--"Time,Value"
+--"Time,Value"
+--"Time,Value"
+...

然后,为了能够使用"RandomName"作为键访问表格中的值:

function Load()
  for key, v in pairs(Table) do
    a = Table[key][RandomName][1] -- 引用"Time"
    b = Table[key][RandomName][2] -- 引用"Value"
    print('Time: ' .. a ..'/' .. 'Value: ' .. b)
  end
end
点赞
用户2226988
用户2226988

你只是没有从表格的深处开始。当你想要在键等于 RandomName 值的表格中获取序列值时,只需要这样做:

function Load()
  for _, v in ipairs(Table[RandomName]) do
    a = v[1] -- 引用 "Time"
    b = v[RandomName][2] -- 引用 "Value"
    print('Time: ' .. a ..'/' .. 'Value: ' .. b)
  end
end

对原始问题的答案:

看起来你想要这样的东西:

Table = { ["[1]othertable"] = {}, ["[2]othertable"] = {} }
table.insert(Table["[1]othertable"],  {TIME, SIGNAL})

键是 "[1]othertable" 和 "[2]othertable"。

你可能更喜欢使用诸如 "othertable1" 和 "othertable2" 的键。如果你使用有效的标识符,你可以省略一些语法:

Table = { othertable1 = {}, othertable2 = {} }
table.insert(Table.othertable1,  {TIME, SIGNAL})

实际上,你可能更喜欢使用 TIME 和 SIGNAL 做类似的事情。你可以使用字符串键而不是正整数索引:

Table = { othertable1 = {}, othertable2 = {} }
table.insert(Table.othertable1,  {TIME = 12.42, SIGNAL = 3.2})
print(Table.othertable1[1].TIME)
2018-02-14 01:08:40