为什么在Lua中排序表格不起作用?

我有一段 Lua 代码生成一个错误,我不明白如何解决它。

  .............................
 local last_num = 0
 local  channelTable={}
 for num in channels.each_number() do  --  channels.each_number() 每次返回 1 个数字
  channelTable[last_num] =num;
  last_num = last_num +1;
 end
 table.sort(channelTable);

根据 Lua 文档,我可以使用 sort 函数对 channelTable 中保存的数字进行排序。我得到的错误是:

尝试对全局变量 'table' 进行索引

有什么解决办法吗,或者应该实现气泡排序?感谢任何提示!

点赞
用户3413723
用户3413723

我认为问题可能在于你期望在每次循环迭代时都调用 channels.each_number()。如果我没弄错的话,我认为它只在程序第一次通过循环时被调用。我相信你在for..in循环中使用的任何东西都需要是一个表格。所以我猜问题在于你的表格没有按照你想要的生成。尝试这样做:

print('channelTable中的项目数 = ' .. #channelTable)

如果结果是0,那么我刚才说的可能就是问题所在。

2015-01-05 12:12:13
用户107090
用户107090

可能是你没有加载表库,或者不小心覆盖了它。

错误信息似乎被截断了:它应该说明为什么索引失败。

2015-01-05 12:13:12
用户3828960
用户3828960

将下面翻译成中文并且保留原本的 markdown 格式

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.

你看到的错误表示 table 库不可用。这个核心库不太可能不属于你的 Lua 环境,所以很可能是你在代码的其他地方分配了一些内容给 table。

2015-01-05 12:13:58