tcoram / bson-lua

BSON in pure Lua.
MIT License
41 stars 13 forks source link

bson (by spec?) orders elements; this implementation doesn't define order of elements #2

Open tcoram opened 11 years ago

tcoram commented 11 years ago

Need to look closer at spec and see what it takes to order elements.

dptole commented 10 years ago

What order the elements is the binary string itself but, in my opinion, the order don't matter because some languages just force a specific sorting of the elements of an array, leaving no option to the developer.

Lua does but JavaScript don't, so I think it's up to the community to take care of that, even though I think it is not an important issue.

LinusU commented 8 years ago

@dptole I cannot possibly think of any language that forces a specific sorting of arrays, mind elaborating a bit?

a = {}

a[1] = "a"
a[2] = "b"
a[3] = "c"

"b" will always be at position 2, the language doesn't force any sorting here?

dptole commented 8 years ago

@LinusU sorry, I didn't express myself well In Lua we don't have arrays or objects as in JavaScript or others, there is just tables which maps any value to any value. If you have a table that looks like an array you can change the values of the already defined indexes and the language will not reorder the array for you.

> a = {1,2,3}
> for k, v in pairs(a) do print(k,v) end
1    1
2    2
3    3
> a[2] = 'foo'
> for k, v in pairs(a) do print(k,v) end
1    1
2    'foo'
3    3

But if you have a table that looks like an object then we start getting strange behaviours.

> a = {lua = 'moon', terra = 'earth', marte = 'mars'}
> for k, v in pairs(a) do print(k,v) end
marte   mars
lua     moon
terra   earth -- It was not displayed the way I defined
> a[1] = 'pluto' -- Strange but possible
> for k, v in pairs(a) do print(k,v) end
marte   mars
1       pluto -- I think this item should not appear here
lua     moon
terra   earth

-- Now let's insert them one by one

> a={lua = 'moon'}
> for k, v in pairs(a) do print(k,v) end
lua     moon -- OK
> a['terra'] = 'earth'
> for k, v in pairs(a) do print(k,v) end
lua     moon
terra   earth -- Nice
> a['marte'] = 'mars'
> for k, v in pairs(a) do print(k,v) end
marte   mars
lua     moon
terra   earth -- Lost the order

If we have an issue about the order of the elements and the language has this behaviour we would have to do a little more work to implement something that, in my opinion again, it is not important at all. At least not now.