Engine
Engine

Reputation: 5422

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.

  .............................
 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. 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!

Upvotes: 1

Views: 225

Answers (3)

Alan
Alan

Reputation: 3002

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.

Upvotes: 1

lhf
lhf

Reputation: 72312

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.

Upvotes: 2

user3413723
user3413723

Reputation: 12223

I think the issue may be that you are expecting channels.each_number() to be called in each iteration of the loop. If I'm not mistaken, I think it only gets called the first time the program goes through the loop. Whatever you use in thefor..in loop needs to be a table, I believe. 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.

Upvotes: 0

Related Questions