1

fala pessoal, estou tentando gravar algumas informações em um .json mas estou recebendo este erro:

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,
}

Função carregada de outro arquivo

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 Resposta 1

2

A função "load_data" falhou, e a variável "rkgdat" foi inicializada com nil.

Você precisa colocar um teste logo após "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

Analisando a lógica de "load_data", provavelmente foi "JSON.decode" que falhou, portanto você precisa também colocar um teste de nil logo após chamar "JSON.decode":

local data = JSON.decode(s)
if not data then data = {} end
return data
1
  • Opa valeu amigo, Resolvido !
    – Santagain
    12/10/2016 às 18:14

Você deve fazer log-in para responder a esta pergunta.

Esta não é a resposta que você está procurando? Pesquise outras perguntas com a tag .