bsky
bsky

Reputation: 20222

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

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?

Upvotes: 1

Views: 1417

Answers (1)

lhf
lhf

Reputation: 72312

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

Upvotes: 3

Related Questions