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

Asked

Viewed 234 times

1

Talk guys, I’m trying to record some information on a . json but I’m getting this error:

date.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

https://core.telegram.org/bots/api http://www.lua.org/pil/21.2.html

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

Analyzing the logic of "load_data", it was probably "JSON.Decode" that failed, so you need to also put a nil test right after calling "JSON.Decode":

local data = JSON.decode(s)
if not data then data = {} end
return data
  • Opa valeu friend, Solved !

Browser other questions tagged

You are not signed in. Login or sign up in order to post.