Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lua table - two entries with same key

I'm not sure how, but we managed to create a table with two keys exactly same. When performing for loop over pairs of the table and printing keys and values we get:

1    true
1    true

and we thought maybe it's a matter of different types or something, so we decided to convert it to json (we use Corona SDK and internal json module).

The result was quite astonishing:

"ourTable" : { "1" : true, "1" : true }

We stored it in a file in order to check the values, and both hex values of "1" were 31.

So another test: convert that json to lua table and... same result as previously: two entries with the same key.

I've never seen anything like that before and to be honest, I don't know how to detect and prevent such situation. We've been using lua & corona for few years and it's the first time we detected something like this, but it's possible that it happened previously and we didn't detect that. It could lead to some incredibly screwed up results.

Corona SDK is using Lua 5.1.

We store this table json encoded in a file. After restarting the app, the file was loaded again and it contained only single entry! Now... this table only contained "id" and boolean, both values exactly the same, but I'm wondering what would happen if the values were different, which one would remain? Tons of scenarios come to my mind now.

I cannot reproduce this issue, but what we do:

  1. Read file with json
  2. Decode json into lua table
  3. Add/update entry in table, simply tab[key] = value
  4. Save file

EDIT: Well, here's now to reproduce the issue:

local d = {true} 
d["1"]=true 
for k,v in pairs(d) do 
    print(k,v) 
end


1   true
1   true
like image 780
Krystian Avatar asked Dec 03 '15 09:12

Krystian


1 Answers

Actually after I added the way to reproduce the issue, it was obvious what happened. The table became mixed.

When I did:

for k,v in pairs(d) do 
    print(k,v, type(k)) 
end

it all made sense:

1   true    number
1   true    string

The only problem we have now is that the json module in Corona SDK changed 1 number into "1" string.

like image 78
Krystian Avatar answered Nov 15 '22 10:11

Krystian