简体   繁体   English

为什么在Lua中对表进行排序不起作用

[英]why does sorting a table in Lua doesn't work

I have a piece of Lua code that generate an error and I don't understand how to solve it. 我有一段生成错误的Lua代码,我不明白如何解决它。

  .............................
 local last_num = 0 
 local  channelTable={} 
 for num in channels.each_number() do  --  channels.each_number() returns 1.number  in each call 
  channelTable[last_num] =num;
  last_num = last_num +1;
 end    
 table.sort(channelTable);

based on lua documentation I can use the function sort to sort the saved numbers in channelTable . 基于lua文档,我可以使用函数sortchannelTable保存的数字进行排序。 the error that I get is: 我得到的错误是:

attempt to index global 'table'

Any idea how can I solve this, or should implement bubble sort? 知道如何解决这个问题,或者应该实现冒泡排序? thanks for any hint! 谢谢你的暗示!

Either you haven't loaded the table library or you have overwritten it by accident. 要么您没有加载表库,要么意外地覆盖了它。

The error message seems truncated: it should say why indexing failed. 错误消息似乎被截断:它应该说为什么索引失败。

The error you are seeing indicates that the table library is not available. 您看到的错误表明表库不可用。 It's unlikely that this core library isn't part of your Lua environment, so it's likely you have assigned something to table elsewhere in your code. 这个核心库不太可能不属于您的Lua环境,因此您可能已经在代码中的其他位置分配了一些内容。

I think the issue may be that you are expecting channels.each_number() to be called in each iteration of the loop. 我认为问题可能是你期望在循环的每次迭代中调用channels.each_number()。 If I'm not mistaken, I think it only gets called the first time the program goes through the loop. 如果我没有弄错的话,我认为它只会在程序第一次通过循环时被调用。 Whatever you use in the for..in loop needs to be a table, I believe. 无论你在for..in循环中使用什么,都需要成为一张桌子,我相信。 So I guess the problem is that your table isn't being generated as you want it to. 所以我想问题是你的表没有按照你想要的那样生成。 Try doing this: 试着这样做:

print('number of items in channelTable = ' .. #channelTable)

If it comes out to 0, then what I said is probably the problem. 如果它出现0,那么我说的可能是问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM