Attempt to index nil with nil while generating terrain?

Heyo, trying to make 3d Perlin noise terrain generation, and while using some sample code i quickly realised if i want crazy things like over hangs i was going to have to use 3d noise. However i have an error in my code. The error comes from

local chunks = {}
 
local function chunkExists(chunkX, chunkY, chunkZ)
	if not chunks[chunkX] then
		chunks[chunkX] = {}
	end
	return chunks[chunkX][chunkY][chunkZ]
end

However, if you need the full script, it can be located at:
https://hastebin.com/awukunoqer.lua
(Keep in mind if you want to test the code yourself, at line 70, you need to remove .."_Dragonoid)

-DR_DOYTEE

1 Like

Similarly to how you are initializing chunks[chunkX] to an empty table with = {}, so must you do for chunks[chunkX][chunkY], for all values of chunkY, otherwise you can’t index into them with [chunkZ] because the tables don’t exist.

You could also replace chunks[chunkX] = {} with return false, and do the same inside an if not chunks[chunkX][chunk] then check after this, if you don’t need to lazily add these empty tables. Personally, I would do this, since it’s a bit weird to populate tables inside a function called “checkExists”, since this kind of implies that it’s a checking function only, not one that will modify data (i.e. it’s the sort of function you’d make const in C++).

1 Like

im sorry but could you explain a bit more?

Emily is saying that chunks[chunkX] = {} does not imply that chunks[chunkX][chunkY] is a table, which you are assuming is the case in your code. Your assumption is the line

return chunks[chunkX][chunkY][chunkZ]

i.e., you are assuming chunks[chunkX][chunkY] = {} is a table.

1 Like