attempt to index local 'rkgdat' (a nil value)

1

Personal speech, I'm trying to write some information in a .json but I'm getting this error:

data.lua: 12: attempt to index local 'rkgdat' (a nil value)

local triggers = {
''
}

local action = function(msg)

local rkgdat = load_data('data/ranking/' .. msg.chat.id .. '.json')

if not rkgdat[msg.from.id] then
rkgdat[msg.from.id] = {
    ['primeiro_nome'] = msg.from.first_name .. ' (' .. msg.from.id ..  ')',
    ['mensagens']     = 1
}

save_data('data/ranking/' .. msg.chat.id .. '.json', rkgdat)
else
rkgdat[msg.from.id] = {
    ['primeiro_nome'] = msg.from.first_name .. ' (' .. msg.from.id ..     ')',
    ['mensagens']     = rkgdat[msg.from.id]['mensagens'] + 1
}

save_data('data/ranking/' .. msg.chat.id .. '.json', rkgdat)
end

return true

end

return {
action = action,
triggers = triggers,
}

Function loaded from another file

load_data = function(filename)

local f = io.open(filename)
if not f then
return {}
end
local s = f:read('*all')
f:close()
local data = JSON.decode(s)

return data

end


save_data = function(filename, data)

local s = JSON.encode(data)
local f = io.open(filename, 'w')
if file==nil then
print("Couldn't open file: "..f)
else
f:write(s)
f:close()
end
end

link link

    
asked by anonymous 12.10.2016 / 18:41

1 answer

2

The "load_data" function failed, and the "rkgdat" variable was initialized with nil.

You need to put a test right after "load_data":

local rkgdat = load_data('data/ranking/' .. msg.chat.id .. '.json')

if not rkgdat then
   return false
end

if not rkgdat[msg.from.id] then
  -- etc

Looking at the load_data logic, it was probably "JSON.decode" that failed, so you also need to place a nil test shortly after calling "JSON.decode":

local data = JSON.decode(s)
if not data then data = {} end
return data
    
12.10.2016 / 18:56