I have to admit it’s a bit strange. Non-defold Lua online interpreters crashes with your example.
I tired this code:
total_orbit_chance = {}
liste_orbitals = {{},{},{},{}}
liste_orbitals[0] = 4
liste_orbitals[1]["chance"] = 50
liste_orbitals[2]["chance"] = 20
liste_orbitals[3]["chance"] = 15
liste_orbitals[4]["chance"] = 10
toc = 0
for i = 1, liste_orbitals[0] do
toc = toc + liste_orbitals[i]["chance"]
table.insert(total_orbit_chance, i, toc)
end
table.insert(total_orbit_chance, 0, toc)
for k, v in pairs(total_orbit_chance) do
print(k, v)
end
and it crashed:
lua: main.lua:15: bad argument #2 to 'insert' (position out of bounds)
stack traceback:
[C]: in function 'table.insert'
main.lua:15: in main chunk
[C]: in ?
And it’s make sense. It should crash, because:
" The table.insert
function inserts an element in a given position of an array, moving up other elements to open space." – table.insert
Since you don’t have index 0, there is nothing to push to right at index 0.
There are two ways to solve this:
a) Change 0 index to 1.
table.insert(total_orbit_chance, 1, toc)
It will work, however each index will be greater by 1 than what you intend.
b) Don’t use table.insert at all and just use:
total_orbit_chance[0] = toc
However in Defold your code does not crashes, instead I have identical result as you:
{ --[[000001AFF5230560]]
0 = 95,
2 = 50,
3 = 70,
4 = 85,
5 = 95
}
Edit: I play’ed a while with this and it seems Defold’s insert works by inserting the whatever index to the table and shifting all indexes greater or equal to inserted to the right, without throwing an error. Try with index -1 for example.
Therefore option b), a.k. changing the line
table.insert(total_orbit_chance, 0, toc)
to:
total_orbit_chance[0] = toc
works perfectly both in Defold and plain Lua.