Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lua: 'pairs' doesn't iterate over [1]

I quickly had to debug something, and wrote following function:

function dumpTable(t)
    for i,v in pairs(t) do
        if type(v) == "table" then
            dumpTable(v)
        else
            print(i..":", v)
        end
    end
end

Now, for some reason

dumpTable({[1]="hello??", [2]="two", {[132]="something", [3.2]="else"}})

outputs

132:    something
3.2:    else
2:  two

notice how the first string is missing? But if I change its key..

dumpTable({["one"]="hello??", [2]="two", {[132]="something", [3.2]="else"}})

it outputs

132:    something
3.2:    else
one:    hello??
2:  two

This is so unintuitive I almost feel like making an idiot of myself not seeing the mistake..

(btw. I do know that my function will overflow the stack if the table contains a recursive reference, going to fix that later)

like image 344
Ancurio Avatar asked Dec 27 '22 13:12

Ancurio


1 Answers

The problem is the inner table. You didn't give it a key, which mean that Lua will give it an array index. Namely, 1. Which will overwrite the [1] key you used for "hello??". So you need to give this table value a proper key, or you need to stop using integer keys for the others.

Or, to put it another way, the following two tables are identical:

{"first", "second", "third"}

{[3] = "third", [2] = "second", "first"} --Note the lack of a key for "first".
like image 107
Nicol Bolas Avatar answered Jan 09 '23 02:01

Nicol Bolas