Insert data from a string into a table

8

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}
    
asked by anonymous 03.05.2014 / 18:43

3 answers

5

Solving the problem.

The best code for inserting the data, as I received it, into the table is as follows:

filecontents = texto1

entries = {}

do

  -- insere os dados do arquivo de texto na tabela

  function entry(entrydata)

      table.insert(entries, entrydata)

  end

  -- carrega os dados do arquivo na forma de código Lua

  thunk = load(filecontents, nil, nil, {entry = entry})
  thunk()

end

the content of text1 being this:

entry{nome="Cassio",sexo="M",idade=19}
entry{nome="Paula",sexo="F",idade=20}

The correct way to display the files in the table is:

for index, tabela in ipairs(entries) do 

    print(tabela.nome)
    ...

end

That way the code works normally. The for will go through the entire entries table, the tabela variable will receive the contents of each row of the table and using that variable you print the data.

    
05.05.2014 / 00:17
6

From what I understand, you're putting tables inside tables, and to call them, you need to pass the numbering on them!

An example:

for i = 1, #dados do 

    print("NOME: ".. dados[i].nome) 
    print("SEXO: ".. dados[i].sexo) 
    print("IDADE: ".. dados[i].idade)
    print("\n") 

end
    
04.05.2014 / 00:04
4

If you already have the contents of the file as a string within Lua and trust that content, then you can use Lua to convert everything to you:

entries = load("return {"..texto:gsub("\n",",").."}")()
    
15.05.2014 / 16:49