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
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).
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.
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...
Me and my stuff True Neutral Aspirant. Why, yes, i do indeed enjoy sarcastically correcting others when they make the most blatant of spelling mistakes. No bullying or trolling the innocent tho.