I have a text file that I read and set it to a string texto
so that it looks like this:
{nome="Cassio",sexo="M",idade=19}
{nome="Paula",sexo="F",idade=20}
And I used the following code to add each line of that string to a position in a table:
dados = {}
for linha in texto:gmatch("[^\r\n]+") do
-- remove a quebra de linha do final da string para inserí-la na tabela
linha = linha:gsub("\n", "")
--insere na tabela
table.insert(dados, linha)
end
The problem is that when I try to print the data from this table, all its data appears as nil
:
for _ in ipairs(dados) do
print("NOME: ", dados.nome)
print("SEXO: ", dados.sexo)
print("IDADE: ", dados.idade)
print("\n")
end
Result:
NOME: nil
SEXO: nil
IDADE: nil
NOME: nil
SEXO: nil
IDADE: nil
How can I fix this?
NOTE: I also tried to use the following code, but the problem is the same, all fields appear as nil
:
filecontents = texto1
entries = {}
do
-- define a function that our data-as-code will call with its table
-- its job will be to simply add the table it gets to our array.
function entry(entrydata)
table.insert(entries, entrydata)
end
-- load our data as Lua code
thunk = load(filecontents, nil, nil, {entry = entry})
thunk()
end
In this case, text1 looks like this:
entry{nome="Cassio",sexo="M",idade=19}
entry{nome="Paula",sexo="F",idade=20}