嵌套表并尝试table.remove时,“期望表,得到字符串”

时间:2019-09-17 12:48:32

标签: lua

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

但是,在运行下面的代码时,它将触发 namespace ConsoleApplication1 { public class Student { public string id; public string name; public string familyName; public string age; } class Program { static void Main(string[] args) { List<Student> studentList=new List<Student>(); do { // ask user if he wants to add more students Console.WriteLine("do you want to add more? if no please write -No- to terminate and see what you have entered. If yes, please enter -Yes-"); string read = Console.ReadLine(); if (read == "No") { /* You can also access List like this * * foreach(Student s in studentList) { Console.WriteLine("id of student {0} is: " s.id); . . . }*/ for (int i = 1; i < studentList.Count(); i++) { Console.WriteLine("id of student {1} is{0}: ", studentList[i].id); Console.WriteLine("name of student {1} is{0}: ", studentList[i].name, i); Console.WriteLine("family name of student {1} is{0}: ", studentList[i].familyName, i); Console.WriteLine("age of student {1} is: {0}", studentList[i].age, i); } break; } else { Student s = new Student(); //Ask for id s.id = Console.ReadLine(); // And same for othre deatil studentList.Add(s); } } while (true); } } } 错误。我不明白为什么会这样。

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

或类似的东西-为什么不这样做,我该怎么解决?

1 个答案:

答案 0 :(得分:1)

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

Lua 5.3 Reference Manual #table.remove

代码中发生的事情是第一个循环没有问题。 在第二个循环中,possiblePorts[i-1]现在为2,因此我们尝试对索引table.remove上的值使用2。在第一个循环中,我们在索引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}