嵌套表和尝试表时"table expected, got string"。删除



我目前正在尝试创建一个表的表,并从上一个嵌套表中删除部分以创建下一个嵌套表,从而将每个嵌套表的长度减少 1。

但是,在运行下面的代码时,它会触发bad argument #1 to 'remove' (got string, expected table)错误。我不明白这是为什么。

possiblePorts = {}
possiblePorts[1] = {"VGA","USB","Ethernet","9mm","HDMI"}
for i=2,5 do
possiblePorts[i] = table.remove(possiblePorts[i-1],math.random(1,5))
end

我希望它创建一个表:

possiblePorts = {
{"VGA","USB","Ethernet","9mm","HDMI"},
{"VGA","Ethernet","9mm","HDMI"},
{"VGA","9mm","HDMI"},
{"9mm","HDMI"},
{"9mm"}
} --formatted for simple viewing

或类似的东西 - 为什么不这样做,我能做些什么来修复它?

table.remove将返回已删除的元素,而不是表的其余元素。

Lua 5.3 参考手册 #table.删除

代码中发生的情况是第一个循环没有问题。 在第二个循环中,possiblePorts[i-1]现在2,因此我们尝试对索引2处的值使用table.remove。我们在索引2处放置的值,在第一个循环中,是一个字符串,因此我们生成错误,试图将其作为table.remove的第一个参数传递。

您也不能在每个表上使用math.random(1,5),因为这会使您有击中数组末尾之外的风险,这将导致来自table.remove的错误。您希望更改数组长度的5

此代码执行您尝试完成的操作

local possiblePorts = {}
possiblePorts[1] = {"VGA","USB","Ethernet","9mm","HDMI"}
for i=2,5 do
possiblePorts[i] = {}
local skip = math.random(1,#possiblePorts[i-1]) -- Get value we will skip at random
local index = 0                                 -- Index for new array
for j=1,#possiblePorts[i-1] do   -- Loop over all the elements of that last array.
if j ~= skip then              -- If the value is not the one we are skipping add it.
index = index + 1
possiblePorts[i][index] = possiblePorts[i-1][j]
end
end
end

for k,v in ipairs(possiblePorts) do
print(k, "{" .. table.concat(v," ") .. "}")
end

输出:

1   {VGA USB Ethernet 9mm HDMI}
2   {USB Ethernet 9mm HDMI}
3   {USB Ethernet HDMI}
4   {Ethernet HDMI}
5   {Ethernet}

相关内容

最新更新