Page 1 of 1
About visit the 2-D Arrays
Posted: Wed Jun 15, 2016 2:13 pm
by poorenglish
Code: Select all
MAP={}
testmap={}
for i=1,10 do
MAP[i]={}
testmap[i]=1
for j = 1,10 do
MAP[i][j]=0
end
print(testmap[0]) --return nil
print(MAP[0][1]) --attempt to index a nil value,why?
end
I created a 1-D arrays testmap and a 2-D Arrays MAP, why I can visit the testmap[0], but I can't visit the MAP[0][1]?
the result should be “nil” too.
thks
Re: About visit the 2-D Arrays
Posted: Wed Jun 15, 2016 2:18 pm
by micha
Both of your for-loops start at 1 and not at 0, so the entries MAP[0] and testmap[0] both do not exist. So if you print them, you get nil. Now MAP[0][1] does not work because MAP[0] is nil, so basically you are trying to access nil[1] and this does not work. If you want to access MAP[0][1], then MAP[0] has to be a table. Currently it is not a table (because it does not exist).
Re: About visit the 2-D Arrays
Posted: Wed Jun 15, 2016 2:25 pm
by poorenglish
thks very much.very clearly explanation.
Re: About visit the 2-D Arrays
Posted: Wed Jun 15, 2016 6:43 pm
by partnano
Maybe it should be noted, just as a little fun fact I guess, that in Lua, while you can start an array with any value you want, it is recommended (
https://www.lua.org/pil/11.1.html) to start arrays with index 1, as all the Lua libraries adhere to this and it's just easier to integrate into everything you could potentially use later on.
Well .. happy coding!
Re: About visit the 2-D Arrays
Posted: Wed Jun 15, 2016 7:05 pm
by zorg
To counter the above, while lua does prefer 1-based indexing (and ipairs starts at 1), luaJIT, that löve uses, is smart enough not to add any speed penalties if one does use 0-based indexing.
Also, again, modular arithmetic is way more complicated looking and less understandable with 1-based indexing than with 0-based (and takes more cycles):
(x+1)%n and (x-1)%n -- simple and understandable, x+1 and x-1 with wrapping.
vs.
(((x-1)+1)%n)+1 and (((x-1)-1)%n)+1 -- x and x-2... then wrap and then add one...