Stuck on optimization script (negative indexing on arrays)

Okay so I have been working on this for a few days and I am completely stuck. I have just found out that negative indexing in roblox does not work as I thought it would. Because of this my code does not work.

I am creating a “chunk system” that loads new parts into the workspace on the client.

Here is the code since it does not work.

local RS = game:GetService("ReplicatedStorage")
local wavePart = RS.WavePart
local module = require(RS.WaveModule)

local Players = game:GetService("Players")
local player = Players.LocalPlayer
local charater = player.Character or player.CharacterAdded:Wait()
local humanoidRootPart = player.Character:WaitForChild("HumanoidRootPart",10)

local RuS = game:GetService("RunService")

local xzSize = 100
local currentXZPosition = {}
local chunks = {}
local renderDistance = 2

wait(5)

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

local function checkSurroundings(position) 
	local flooredX, flooredZ = math.floor(humanoidRootPart.Position.X/xzSize) , math.floor(humanoidRootPart.Position.Z/xzSize)
	if currentXZPosition[1] == flooredX and currentXZPosition[2] == flooredZ then
	else
		for iX = flooredX - renderDistance , flooredX + renderDistance do
			for iZ = flooredZ - renderDistance ,  flooredZ + renderDistance do
				if not chunkExists(iX,iZ) then
					
					chunks[iX][iZ] = module:AddSection(iX,iZ)
				end
			end
		end	
		--print(chunks)
		print("I AM AT:",flooredX,",",flooredZ)
		for iX,vX in ipairs(chunks) do
			for iZ,vZ in ipairs(chunks[iX]) do
				print("Scanning:",iX,iZ)
				if iX > flooredX + renderDistance or iZ > flooredX + renderDistance or  iX < flooredX - renderDistance or iZ < flooredX - renderDistance  then
					--module:RemoveSection(chunks[iX][iZ])
					print("Section ",iX,",",iZ," is outside boundaries.")
					vZ.BrickColor = BrickColor.new("Black")--check which blocks would be deleted.
					--[[chunks[iX][iZ]:Destroy()
					chunks[iX][iZ] = nil]]
				else
					print("Section ",iX,",",iZ," is within boundaries.")
					print("X axis is at ",flooredX + renderDistance," to ",flooredX - renderDistance)
					print("Z axis is at ",flooredZ + renderDistance," to ",flooredZ - renderDistance)

				end
			end		
		end	
		currentXZPosition = {flooredX,flooredZ}
	end
end

--[[RuS.Stepped:Connect(function()
	checkSurroundings(humanoidRootPart.Position)
end)]]


while wait(1) do
	checkSurroundings(humanoidRootPart.Position)
end


Any feedback on how I can make negative indexing possible or probably a better way for me to make a chunk loading script would be appreciated.
Thanks for reading.

You could probably try this:

-- example
local metatable = {}

metatable.__index = function(self, index)
    if type(index) == "number" and index < 0 then
        -- checks the index to see if it's a negative number
        return self[#self + index] -- returns the index by doing ( #table + (-num) )
    end

    return self[index] -- returns what it normally would if none of the conditions passed
end

local meta = setmetatable({}, metatable)
-- create a metatable

for i = 1, 10 do
   -- insert 10 values into the table (for testing)
   table.insert(meta, i)
end

print(meta[-2]) -- prints '8'

Negative indexing is possible if you use strings instead of numbers as the dictionary name. You can convert between the strings and numbers with tostring() and tonumber().
**Note that you won’t be able to use ipairs on the table with this method.

example:

local t = {}
for i = -25, 25 do --iterate from -25 to 25
  t[tostring(i)] = 'random value' --create indexes
end

--test it by printing out the contents
for k, v in pairs(t) do
  print(tonumber(k), v)
end

Or you can call for the values manually:

local t = {['-25'] = 'random value'}
t['-24'] = 'random value'

print(t[tostring(-25)])
print(t[tostring(-24)])
1 Like

Thanks for this. It is a simple solution to my code. This works and it is very effective. I have managed to finish the program. To be honest I didn’t realize the solution could be so simple.

Thanks for your help.