Save table value

Asked

Viewed 165 times

4

I would like to save the value assigned to a table in real time, I will explain.

I have 2 files:

Main moon.

dofile("tester.lua")

io.write("blabla")

table.insert(oi, io.read())

print(oi[1])

io.read()

Tester.moon

oi = {}

If I run and write: kkk return -> kkk But when closing the program, it is not saved in the file. How do I keep the value added to the table?

  • I am running in prompt mode. .

  • My question was kind of stupid... I who was stupid... Focusing on more than one thing at the same time is not working very well... =/

1 answer

5


It may be interesting to open the file in a variable and edit the file by it at the end of the run:

dofile("tester.lua")
arquivo = assert(io.open("tester.lua", "w"), "Falha ao abrir arquivo") -- O assert é apenas caso possa dar algum erro, mas caso prefira, descomente a linha abaixo e comente essa!
--arquivo = io.open("tester.lua", "w")
io.write("blabla")
table.insert(oi, io.read())
print(oi[#oi])

texto = "oi = {"
for i = 1, #oi do
    texto = texto.."\""..tostring(oi[i]).."\""
    if not (i == #oi) then
        texto = texto..", "
    end
end
texto = texto.."}"

arquivo:write(texto)
arquivo:flush()
io.close(arquivo)
io.read()

This way, it will insert in the table the data that are passed at the prompt.

  • Gammeth, I don’t think you understand, I want to add a value to the table created in 'Tester.lua' and keep it there. Anyway, thanks.

  • @Gabrielsales I think I started to understand your problem, but to be sure what I should answer, answer me: In this case, you intend to add several values in the table, and each time you run it adds another file, correct?

  • Almost that, but no longer adds a file, just saves the value in the file Tester.lua, inside the table.

  • @Gabrielsales changed my answer. This is how you want?

  • Perfect, thank you. .

Browser other questions tagged

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