Lua: Yield error: attempt to index a nil value (local 'f') - lua

I'm completely unfamiliar with Lua and I need to work with some Lua code.
I have the following method where I pass in a file and I want to read the contents of that file as a string.
function readAll(file)
local io = require("io")
local f = io.open(file, "rb")
local content = f:read("*all")
f:close()
return content
end
For that, I'm getting:
Lua: Yield error: [string "myFile.lua"]:101: attempt to index a nil value (local 'f')
The error appears on this row:
local content = f:read("*all")
Any idea what could be causing this?

The error means that io.open failed. To see why, try
local f = assert(io.open(file, "rb"))
or
local f,e = io.open(file, "rb")
if f==nil then print(e) return nil end

Related

Roblox Error: attempt to index local 'screengui' (a nil value)

Workspace.Part.Script:16: attempt to index local 'screengui' (a nil value)
wait(2) -- Testing to make sure assets loaded
script.Parent.Touched:connect(function(hit)
if not hit or not hit.Parent then return end
local human = hit.Parent:findFirstChild("Humanoid")
if human and human:IsA("Humanoid") then
local person = game.Players:GetPlayerFromCharacter(human.parent)
if not person then return end
person.Checklist.FirstEggCollected.Value = true
local playgui = person:FindFirstChild('PlayerGui')
print(playgui)
wait(0.2)
local screengui = playgui:FindFirstChild('ScreenGui')
wait(0.2)
print(screengui) -- This prints nil
local collectnotice = screengui:FindFirstChild('CollectionNotice') -- This is line 16
local Toggle = collectnotice.Toggle
local text = Toggle.Text
local value = text.Value
value = "The Easy Egg!"
person:WaitForChild('PlayerGui'):FindFirstChild('ScreenGui'):FindFirstChild('CollectionNotice').Toggle.Color.Value = Color3.fromRGB(0,255,0)
person:WaitForChild('PlayerGui'):FindFirstChild('ScreenGui'):FindFirstChild('CollectionNotice').Toggle.Value = true
script.Parent:Destroy()
wait(5)
game.Workspace.Variables.IfFirstEggInGame.Value = false
end
end)
I've been at this for hours. No idea how to make the error fix. FE is on, Yes its name is "ScreenGui" and it is inside "PlayerGui"
Error: Workspace.Part.Script:16: attempt to index local 'screengui' (a nil value)
From the Roblox manual: http://wiki.roblox.com/index.php?title=API:Class/Instance/FindFirstChild
Description: Returns the first child found with the given name, or nil
if no such child exists.
So there seems to be no child named "ScreenGui".
If a function may return nil you have to handle that properly. Blindly indexing possible nil values is bad practice.
Your issue is at the line local collectnotice = screengui:FindFirstChild('CollectionNotice').
You do not have an instance listed for the screengui variable.

Does Luci have print function?

I want to print my parsing value at Luci.
Here is my code.
local val = {}
mm = Map("test", translate("For TEST"))
test=mm:section(TypedSection, "test", translate("TEST"))
test.anonymous = true
test.addremove = false
rssis = test:option(DummyValue, "rssi", translate("RSSI"))
t = test:option(DummyValue, "tx", translate("TX"))
r = test:option(DummyValue, "rx", translate("RX"))
local f = io.popen("iwpriv wlan0 stat")
for line in f:lines() do
for s in line:gmatch("(%S+)%s") do
table.insert(val, s)
end
for i, v in ipairs(val) do
end
end
f:close()
rssis:value(val[35])
if val[41] == "6M" then
t:value(val[41], translate("Disconnect"))
else
t:value(33, translate("Good"))
end
if val[49] == "6M" then
r:value(val[49], translate("DIsconnect"))
else
r:value(33, translate("GOOD"))
end
return mm
I saw the DummyValue which Creates a readonly field in the form.
So I used it instead of print function.
However it has errors "attempt to index global 'rssis' (a nil value)"
Only in lua file(not used for Luci) If i used the print function, it has no error. Does Luci has print function?
There is a luci.util.perror("blah blah") function that prints to the syslog.
you can then use the shell command "logread" to display in a console.
I guess this is what you need to debug your code.

Meta table error

I am trying to set up a toy example for threading in torch but I am getting an error from running the code below. I think it might just be the way I set up the table but I am not sure.
Threads = require 'threads'
Threads.serialization('threads.sharedserialize')
DataThreads = {}
DataThreads.__index = DataThreads
local result = {}
local unpack = unpack and unpack or table.unpack
function DataThreads.new(nThreads,opt_)
local self = {}
opt_ = opt_ or {}
self.threads = Threads(nThreads,
function()
print("background stuff")
end
)
self.threads:synchronize()
-- The below for loop is causing the error but the same :addjob() works later on
for i=1, nThreads do
self.threads:addjob(self._getFromThreads, self._pushResult)
end
return setmetatable(self,DataThreads)
end
function DataThreads._getFromThreads()
x,y = torch.uniform(),torch.uniform()
return x,y
end
function DataThreads._pushResult(...)
local res = {...}
if res == nil then
self.threads:synchronize()
end
result[1] = res
end
function DataThreads:getBatch()
self.threads:addjob(self._getFromThreads, self._pushResult)
self.threads:dojob()
local res = result[1]
result[1] = nil
if torch.type(res) == 'table' then
return unpack(res)
end
print(type(res))
return res
end
d = DataThreads.new(4)
The error occurs in :addjob() in the .new function. However calling the same :addjob() later on in the :getBatch() function works. Am I not allowed to call the ._getFromThreads(), ._getFromThreads() functions before the metatable is set? Here is the error, which I think means ._getFromThreads() is not returning anything;
/home/msmith/torch/install/bin/luajit: ...e/msmith/torch/install/share/lua/5.1/threads/threads.lua:215: function callback expected
stack traceback:
[C]: in function 'assert'
...e/msmith/torch/install/share/lua/5.1/threads/threads.lua:215: in function 'addjob'
threads.lua:21: in function 'new'
threads.lua:54: in main chunk
When the code in your new function runs the metatable hasn't been set up yet so when you use self._getFromThreads and self._pushResult there's nothing there and you get nil back and that's not valid.
It works after the new function returns because at that point the metatable has been added so the lookups use the __index metamethod to look the entries up.
You can do
local self = setmetatable({}, DataThreads)
to set the metatable up immediately and then just
return self
at the end.

Scanning folders using lua

I'm trying to get the name of all the file saved in two folders, the name are saved as :
1.lua 2.lua 3.lua 4.lua and so on
the folders name are :
first folder : "/const/"
second folder: "/virt/"
what I'm trying to do is only get the number of the files and this works but not in the right order, when I get the 17 file for example I get the 17th delivered from the function before the 15 and this causes for me a problem here the code of the function that I'm using :
local virt_path = "/virt/"
local const_path = "/const"
local fs = require "lfs"
local const = {}
for num = 1, (numberoffile)do -- numberoffile is predfined and can't be change
const[num] = assert(
dofile (const_path .. mkfilename(num)),
"Failed to load constant ".. num ..".")
end
local function file_number() --this is the function that causes me a headach
local ci, co, num = ipairs(const)
local vi, vo, _ = fs.dir(virt_path)
local function vix(o)
local file = vi(o)
if file == nil then return nil end
local number = file:match("^(%d+).lua$")
if number == nil then return vix(o) end
return tonumber(number)
end
local function iter(o, num)
return ci(o.co, num) or vix(o.vo, num)
end
return iter, {co=co, vo=vo}, num
end
As I said the function delive the need return values but not the right Arithmetic order.
any idea what I'm doing wrong here ?
I use my path[1] library.
1 We fill table with filenames
local t = {}
for f in path.each("./*.lua", "n") do
t[#t + 1] = tonumber((path.splitext(f)))
end
table.sort(t)
for _, i in ipairs(t) do
-- do work
end
2 We check if files exists
for i = 1, math.huge do
local p = "./" .. i .. ".lua"
if not path.exists(p) then break end
-- do work
end
[1] https://github.com/moteus/lua-path

How to read data from a file in Lua

I was wondering if there was a way to read data from a file or maybe just to see if it exists and return a true or false
function fileRead(Path,LineNumber)
--..Code...
return Data
end
Try this:
-- http://lua-users.org/wiki/FileInputOutput
-- see if the file exists
function file_exists(file)
local f = io.open(file, "rb")
if f then f:close() end
return f ~= nil
end
-- get all lines from a file, returns an empty
-- list/table if the file does not exist
function lines_from(file)
if not file_exists(file) then return {} end
local lines = {}
for line in io.lines(file) do
lines[#lines + 1] = line
end
return lines
end
-- tests the functions above
local file = 'test.lua'
local lines = lines_from(file)
-- print all line numbers and their contents
for k,v in pairs(lines) do
print('line[' .. k .. ']', v)
end
You should use the I/O Library where you can find all functions at the io table and then use file:read to get the file content.
local open = io.open
local function read_file(path)
local file = open(path, "rb") -- r read mode and b binary mode
if not file then return nil end
local content = file:read "*a" -- *a or *all reads the whole file
file:close()
return content
end
local fileContent = read_file("foo.html");
print (fileContent);
Just a little addition if one wants to parse a space separated text file line by line.
read_file = function (path)
local file = io.open(path, "rb")
if not file then return nil end
local lines = {}
for line in io.lines(path) do
local words = {}
for word in line:gmatch("%w+") do
table.insert(words, word)
end
table.insert(lines, words)
end
file:close()
return lines;
end
There's a I/O library available, but if it's available depends on your scripting host (assuming you've embedded lua somewhere). It's available, if you're using the command line version. The complete I/O model is most likely what you're looking for.

Resources