About visit the 2-D Arrays

Questions about the LÖVE API, installing LÖVE and other support related questions go here.
Forum rules
Before you make a thread asking for help, read this.
Post Reply
poorenglish
Prole
Posts: 47
Joined: Thu Sep 24, 2009 1:49 pm

About visit the 2-D Arrays

Post by poorenglish » Wed Jun 15, 2016 2:13 pm

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

User avatar
micha
Inner party member
Posts: 1083
Joined: Wed Sep 26, 2012 5:13 pm

Re: About visit the 2-D Arrays

Post by micha » Wed Jun 15, 2016 2:18 pm

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).

poorenglish
Prole
Posts: 47
Joined: Thu Sep 24, 2009 1:49 pm

Re: About visit the 2-D Arrays

Post by poorenglish » Wed Jun 15, 2016 2:25 pm

thks very much.very clearly explanation.

User avatar
partnano
Prole
Posts: 20
Joined: Sat Jun 11, 2016 4:53 pm
Location: twitter.com/partnano
Contact:

Re: About visit the 2-D Arrays

Post by partnano » Wed Jun 15, 2016 6:43 pm

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!

User avatar
zorg
Party member
Posts: 2995
Joined: Thu Dec 13, 2012 2:55 pm
Location: Absurdistan, Hungary
Contact:

Re: About visit the 2-D Arrays

Post by zorg » Wed Jun 15, 2016 7:05 pm

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 :3True 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.

Post Reply

Who is online

Users browsing this forum: nikneym and 32 guests