1

i started learning lua and now i'm trying to deal with nested tables.

Basically i want to create a kind of local "database" using json interaction with lua (i found out that was the best thing to store my values)...

what i supposed to do is to scan all members inside a chatgroup (i'm using an unofficial telegram api) and store some values inside a table. I was able to retrieve all datas needed, so here's the structure declared in main function:

local dbs = load_data("./data/database.json")

dbs[tostring(msg.to.id)] = {
        gr_name = {},
        timestamp = "",
        user = {               --user changes into user ids
            us_name = {},
            us_nickname = {},
            us_role = ""
        },
    }

where msg.to.id contains a valid number. This is what i tried to do:

dbs[tostring(id)]['users'][tostring(v.peer_id)]['us_nickname'] = v.username

this one works but this one:

dbs[tostring(id)]['users'][tostring(v.peer_id)] = table.insert(us_name,v.print_name)

(id is a correct number and matches with first field, same as all values passed like v.peer_id and v.print_name so those are not the problem)

gives error "table expected"... i'm pretty sure i have totally no idea of how to insert an element in such a table like mine.

Can anyone of you be so kind to help me? I hope to be clear enough explaining my issue.

Thanks in advance to everyone :)

3
  • 1
    It is not clear what you are trying to do. table.insert is for arrays, and you don't have one. Are you trying to create a table to add to users? Commented Mar 15, 2016 at 19:47
  • table.insert inserts a value into a table and doesn't return anything. Commented Mar 15, 2016 at 20:13
  • a single user can change names so i want to store the new value without overwrite it in field us_names... i thought the best way was to declare an array of us_names ad to use table.insert in that field to store without overwrting previous value Commented Mar 15, 2016 at 21:30

1 Answer 1

1

To add new user name to an existing user you probably want to insert it into the sub-table like this:

table.insert(dbs[tostring(id)]['users'][tostring(v.peer_id)].us_name, v.print_name)
Sign up to request clarification or add additional context in comments.

1 Comment

yea solved thanks :) i found out that in fact table.insert does not need to be assigned like i did, using equals.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.