Using a function in a module script, I am getting a nil value that is confusing the lights out of me. Can someone help me debug this? I am using this function to produce a 6 digit string/integer key for a table index. The zVal is nil when passed to the function for some reason. the xVal was passed properly, however.
Error: ReplicatedStorage.MazeDataGenerator:63: attempt to compare number with nil
Module Script:
function module:GetIndexKey(xVal, zVal)
local xStr = ''
local zStr = ''
--zVal is nil, even though 0 was passed in the argument; added this if statement prevent nil error
if xVal ~= nil and zVal ~= nil then
if xVal >= 0 and xVal <= 9 then
xStr = "00" .. tostring(xVal)
elseif xVal > 9 and xVal <= 99 then
xStr = "0" .. tostring(xVal)
else
xStr = xVal
end
if zVal >= 0 and zVal <= 9 then -- The error occurs here if I don't have the nil check
zStr = "00" .. tostring(zVal)
elseif zVal > 9 and zVal <= 99 then
zStr = "0" .. tostring(zVal)
else
zStr = tostring(zVal)
end
else
print ("nil values in xVal or zVal")
print (xVal)
print (zVal)
end
return (xStr .. zStr)
end
Calling function:
for x = 0,_sizeX do
for z = 0,_sizeZ do
-- Here, z = 0 in the first loop
local indexKey = mazeDataGenerator.GetIndexKey(x, z)
print(indexKey)
if mazeData[indexKey] == 0 or mazeData[indexKey] == nil then
msg = msg .. "..."
else
msg = msg .. "=="
end
end
msg = msg .. "\n"
end
print(msg)

1 comment
Check out https://developer.roblox.com/articles/Understanding-Functions-in-Roblox for additional information, btw. I suggest looking at "Functions Within Tables" and "Methods". They're different types of functions. I forgot to include that in my answer, it's pretty important stuff!