This is a read-only snapshot of the ComputerCraft forums, taken in April 2020.
Sjaelly's profile picture

Newbie - attempt to get length of nil

Started by Sjaelly, 05 October 2015 - 02:53 PM
Sjaelly #1
Posted 05 October 2015 - 04:53 PM
Hey, i would like some help/understanding with what is causing this problem. It keeps returning "attempt to get length of nil" at the line "MasterTable[#MasterTable+1] = Settings"


MasterTable = {}

if not fs.exists("settings") then
local FileCreating = io.open("settings", "w")
FileCreating:write()
FileCreating:close()
end

function FileWrite()
local FileInput = io.open("settings", "w")
FileInput:write(textutils.serialize (MasterTable))
FileInput:close()
end

function FileRead()
local FileOutput = fs.open("settings","r")
local Filedata = FileOutput.readAll()
FileOutput.close()
return textutils.unserialize(Filedata)
end

function Input()
Settings = {}
for i=1,3 do
Settings[#Settings+1] = io.read()
end
textutils.tabulate(Settings)
MasterTable[#MasterTable+1] = Settings
FileWrite()
shell.run("startup")
end


MasterTable = FileRead()
Input()

Have a nice day. :D/>
valithor #2
Posted 05 October 2015 - 05:28 PM
One thing to note is that if what is passed to textutils.unserialize can not be unserialized into a table, then it returns nil. So it appears your FileRead function is returning nil, thus setting MasterTable to nil. Make sure that the Settings file is a serialized table, or can be unserialized.

A little error check you could add in case the settings file does not exist and you just created it.

local readFile = FileRead()
MasterTable = type(readFile)=="table" and readFile or {}

That is essentially a short hand of doing:

local readFile = fileRead()
if type(readFile) == "table" then
  MasterTable = readFile
else
  MasterTable = {}
end

Also just going to mention that you can also use table.insert(table,value) as a alternative to table[#table+1] = value.
Edited on 05 October 2015 - 03:29 PM
Sjaelly #3
Posted 05 October 2015 - 07:15 PM

local readFile = FileRead()
MasterTable = type(readFile)=="table" and readFile or {}

That is essentially a short hand of doing:

local readFile = fileRead()
if type(readFile) == "table" then
  MasterTable = readFile
else
  MasterTable = {}
end

That did the trick, awesome many thanks. ;)/>