Lua nested tables, table.insert function - lua

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 :)

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)

Related

Dexie eachUniqueKey and Where Clause

I'm developing an application in Quasar/Electron and using Dexie/IndexedDB for my database. I want to find all distinct records in the database that contain both my Event ID and a Dog ID (both key indexed fields). I am able to do this with the following code:
await myDB.runTable
.orderBy('[fk_event+fk_dog]')
.eachUniqueKey((theDuo) => {
this.runsArray.push({eventID: theDuo[0], dogID: theDuo[1]})
})
I'm using a combined key which is working well. However, I need to have more of the records than just the keys. I need a few more fields, is this possible?
I was trying to get records with the unique key function while also using the where function, but that doesn't seem to work.
I need to get all the unique (distinct?) dogs in the table that are in a particular event. And also get their corresponding information. I'm not sure if there is a better, more efficient way to do this? I can always pull out all the records and loop through them to build a custom array, I was just hoping to do this at the table read level. (yeah I'm still in tables/records even though these are collections etc. :p ).
Even the above code gives me all the events, and I can pull out what I need with a filter. I just was thinking it would be faster and more efficient to do it at the read level.
this.enteredRuns = this.runsArray.filter((theEvent) => {
return ( (theEvent.eventID == this.currentEventID) )
})
Try
await myDB.runTable
.orderBy('[fk_event+fk_dog]')
.clone({unique: "unique"})
.toArray()
I know this isn't documented but it should do the work to use unique cursor while still extracting the whole objects and not just the keys. You cannot combine with where but you could use .filter. Just be aware that not all records with be scanned as it will jump over records with same keys - selecting the first visited records only.

Different ways of inserting into a table LUA

Okay, so i come down to a dilemma that I can't seem to solve in LUA.
Basically I am trying to insert values into a table, and i am trying to insert it like this:
activeContracts = {
[user_id] = {
[1] = {
source = src
}
}
}
But not in that style but instead of this style:
activeContracts = {}
activeContracts[user_id][1]["source"] = src
But the last example doesn't work. I've googled around and I can't seem to find any documentation that displays my dilemma.
If anyone experienced in LUA can comment on this it would mean alot.
Regards.
activeContracts = {} creates an empty global table.
activeContracts[user_id][1]["source"] = src attempts to assign scr to activeContracts[user_id][1]["source"] But you may not index activeContracts[user_id][1] because it does not exist.
You may also not index activeContracts[user_id] for the same reason.
So you're trying to assign values to a nested tables that do not exist. You have to create that nested structure first. You're basically trying to enter a room in the third floor of a house you never built.
activeContracts = {[user_id] = {{}}}

Understanding how to access objects in lua

The closest i've gotten to figuring this out, came from this post Understanding how to access values in array of tables in lua which actually has the most useful information i've seen. However, I'm still running into a minor issue that I hope someone could help me make more sense of it.
As the title states, I'm trying to access an object in lua. I've learned that dot notation doesn't work, so the alternative is to use [] brackets. I have this object here that I can't seem to access.
[1] = ▼ {
["CopperOre"] = ▼ {
["Counter"] = 0,
["Earned"] = 0
}
}
This was a paste from the ROBLOX studio console, for those who are familiar with it. This object can easily be seen by calling the object name print(obj)
However, I can't seem to access anything inside of the object. obj.CopperOre returns nil, same with obj['CopperOre']
How exactly do I access the parts of the object?
You are forgetting to pass the index into the obj array to access the object stored there.
So to properly access the CopperOre table, you need to reference it like this :
print(obj[1].CopperOre)
-- or
print(obj[1]["CopperOre"])

Updating username across database

I've just started developing an app and having played about with Firebase before I figured it'd be a useful solution to having data stored server side.
I'm at the point where I've got a fully functional login and registration system which takes you to the app, but I've made it so that you require a 'username' before you can get passed the 'further registration' page (where the user sets up their profile information).
Currently, I've got a little note telling the user that they will be unable to update their username after setting it - however I don't really like the idea of this although I feel like I have no choice which is why I'm asking.
If I have multiple uses of the username in multiple places, like so:
{
users: {
id1234: {
username: "SomeUser123",
age: 20
}
}
posts: {
id445: {
title: "Some title",
content: "Some content",
postedBy: "someUser123"
}
}
}
How would I go about updating that person's username so that it also updates the post's username field (and likely several other places) in Swift? Or would the best option be to not allow a user to update their name? Which would be a shame.
Two Methods come to mind
1. Easy Route
If you're certain that you'll only be using username in those two places, then I'd just create references to them and simply update their value. This method is easy but obviously not scalable.
let userReference = FIRDatabase.database().reference().child("users/id1234")
userReference.updateChildValues([
"values": [
"sample0",
"sample1"
]
])
For the posts one, you'd want to filter first by postedBy before updating the value
2. Multi-path Route
This is the most scalable option and I'd recommend you reading this blog about it.
You can use updateChildValues for that.
let uniqueId = "id1234" //In your case
let newName = "NewUserName"
let ref = FIRDatabase.database().reference().child("users").child(uniqueId)
ref.updateChildValues(["username":newName])
Or you can also use setValue for single field update
ref.setValue(["username":newName])
Perhaps the easiest way is to store everything using the Firebase uid, but maintain a separate table of displayName for each uid, and then use the uid for the data layer, and displayName for the presentation layer.
This way, you only have to maintain the displayName in one place.

Querying TAFFYDB nested records

I have created a data model using TAFFYDB. Some of the fields have nested records. I am facing difficulties querying and updating the nested records.
For example:
var friends = TAFFY([
{
"id":1,
"gender":"M",
"first":"John",
"last":"Smith",
"city":"Seattle, WA",
"comp":
[
{
"id":1,
"audience":"cavern"
},
{
"id":2,
"audience":"cottage"
}
]
},
{
"id":2,
"gender":"F",
"first":"Basic",
"last":"Smith",
"city":"Seattle, WA",
"comp":
[
{
"id":1,
"audience":"bush"
},
{
"id":2,
"audience":"swamp"
}
]
}
]);
Supposing I need to update any of the comp field's audience, how will I go about it?
With regards to queries:
When you have simpler nested arrays, you should be able to select specific records using the has and hasAll methods. However, there is an open issue that states neither of these methods work correctly. There are commits but since the issue has been left open, I assume they are not 100% fixed.
For for complex nested data, like your example, the only thing I found was this old mailing list conversation talking about some sort of find method. No such method seems to exist though nor is there any mention of it in the docs.
With regards to updates:
You should be able to update the "comp" data by passing in the modified JSON that goes with it (assuming you are able to get the data out of the db in the first place) into a normal update. However, there is an open bug showing that update does not work when record values are objects. So even if you were able to query the data and were able to modify it, you wouldn't be able to update a record anyway because of the bug. You can however do a remove and an insert.
Despite what I found above, I did some testing and found that you can update files by passing in objects. So this is a quick example of how to do a simple update:
// To show what TAFFYDB looks like:
console.log(friends().stringify());
"[{"id":1,"gender":"M","first":"John","last":"Smith","city":"Seattle, WA","comp":[{"id":1,"audience":"cavern"},{"id":2,"audience":"cottage"}],"___id":"T000003R000002","___s":true},{"id":2,"gender":"F","first":"Basic","last":"Smith","city":"Seattle, WA","comp":[{"id":1,"audience":"bush"},{"id":2,"audience":"swamp"}],"___id":"T000003R000003","___s":true}]"
// Get a copy of the comp file from the database for what you want to modify.
// In this example, let's get the **first** record matching people with the name "John Smith":
var johnsComp = friends({first:"John",last:"Smith"}).first().comp;
// Remember, if you want to use select("comp") instead, this will return an array of results.
// So to get the first result, you would need to do this despite there being only one matching result:
// friends({first:"John",last:"Smith"}).select("comp")[0];
// There are no nested queries in TAFFYDB so you need to work with the resulting object as if it were normal javascript.
// You should know the structure and you can either modify things directly, iterate through it, or whatever.
// In this example, I'm just going to change one of the audience values directly:
johnsComp[0].audience = "plains";
// Now let's update that record with the newly modified object.
// Note - if there are more than one "John Smith"s, then all of them will be updated.
friends({first:"John",last:"Smith"}).update({comp:johnsComp});
// To show what TAFFYDB looks like after updating:
console.log(friends().stringify());
"[{"id":1,"gender":"M","first":"John","last":"Smith","city":"Seattle, WA","comp":[{"id":1,"audience":"plains"},{"id":2,"audience":"cottage"}],"___id":"T000003R000002","___s":true},{"id":2,"gender":"F","first":"Basic","last":"Smith","city":"Seattle, WA","comp":[{"id":1,"audience":"bush"},{"id":2,"audience":"swamp"}],"___id":"T000003R000003","___s":true}]"
For a better targeted query or update (something that perhaps acts like a nested query/update), you can possibly try passing in a function. If you look at the docs, there is a simple example of this for update():
db().update(function () {this.column = "value";return this;}); // sets column to "value" for all matching records
I have an example, in this case i made an update to a nested field.
To acces the data you can do like this:
console.log( JSON.stringify(
data({'id':'489'}).get()[0].review[0][0].comments
))
This is an example how it works

Resources