Insert string data into a table

Asked

Viewed 644 times

8

I have a text file that I read and adjusted in a string texto so that it would stay that way:

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

And I used the following code to add each row of that string to a table position:

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 the data from it appears as nil:

for _ in ipairs(dados) do 

    print("NOME: ", dados.nome) 
    print("SEXO: ", dados.sexo) 
    print("IDADE: ", dados.idade)
    print("\n") 

end  

Upshot:

NOME:   nil
SEXO:   nil
IDADE:  nil


NOME:   nil
SEXO:   nil
IDADE:  nil 

How to fix this problem?


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 is like this:

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

3 answers

6

From what I understand, you’re putting tables inside tables, and to call them, you need to pass her numbering!

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

5


Solving the problem.

The best code for entering the data, the way I received it, in the table, is the following:

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 contents of the text1 being this:

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

The correct way to display the table files is:

for index, tabela in ipairs(entries) do 

    print(tabela.nome)
    ...

end

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

4

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

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

Browser other questions tagged

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