Issue with tables

there must be something wrong with tables and the pairs function…
I was trying to count up how many touches were in a table (indexed by their id) and it doesn’t work whereas it does in older projects.
so I wrote a little test, suspecting there’s something wrong with pairs
then I discovered that assigning nil to a table element doesn’t quite work as expected either…
version: 3.8.1 (383)

-- pairs Test
function setup()
    t1 = {0,0,0} --automatically indexed
    t2 = {a=0,b=0,c=0} --manually indexed
    t3 = {0,0,0,0} ; t3[1] = nil --deleted first entry
    t1c = #t1 
    t2c = #t2
    t2c2 = 0 ; for k,v in pairs(t2) do t2c2 = t2c2+1 end  
    t3c = #t3
    t3c2 = 0 ; for k,v in pairs(t2) do t3c2 = t3c2+1 end
      "table 1 count 1: "..t1c..
    "\ntable 2 count 1: "..t2c..
    "\ntable 2 count 2: "..t2c2..
    "\ntable 3 count 1: "..t3c..
    "\ntable 3 count 2: "..t3c2


table 1 count 1: 3
table 2 count 1: 0
table 2 count 2: 3
table 3 count 1: 4
table 3 count 2: 3

If you head over to Lua’s online demo and paste your code there, you’ll get the same results as you do in Codea: Lua: demo’s output:

table 1 count 1: 3
table 2 count 1: 0
table 2 count 2: 3
table 3 count 1: 4
table 3 count 2: 3


Tables contain 2 parts:

  • An integer indexed part (the ordinary array part)
  • A map part indexed with any other Lua object (the associative array part)

The # operator returns the number of elements in the ‘array’ part and the pairs function on the map part. The array variant is ipairs.

See this stack overflow question for more details.

wait… I… I don’t know what had me confused.
I understand tables and pairs and ipairs and #
…>~< maybe I’m just tired or distracted…
the issue I had in my other code must have another cause…

it was a stupid capitalization typo :woman_facepalming:

thinking of deleting this as there isn’t actually any bug, it was just a misunderstanding on my part, sorry

1 Like

A huge part of coding is learning from mistakes. Especially for those of us who couldn’t attend university and get those years of experience.

It’s not a bug, but we learned something. I think that’s dandy :partying_face:

it’s a common issue with Lua and people need to learn it so it’s good to keep this thread, i have learned a lot from old threads here

think of a sequential table as a list/array and a table with defined keys as a table/object/hash

in Lua the default table is a list (1, 2, 3, etc) but when you break the table from being sequential it breaks table from a list into a hash, whereas previously ipairs works now you must use pairs