Jump to content




Newbie - attempt to get length of nil

computer lua help

  • You cannot reply to this topic
2 replies to this topic

#1 Sjaelly

  • New Members
  • 2 posts

Posted 05 October 2015 - 03: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

#2 valithor

  • Members
  • 1,053 posts

Posted 05 October 2015 - 04: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 by valithor, 05 October 2015 - 04:29 PM.


#3 Sjaelly

  • New Members
  • 2 posts

Posted 05 October 2015 - 06:15 PM

View Postvalithor, on 05 October 2015 - 04:28 PM, said:


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





1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users