I got a table of form let's say:
house = {
["Street 22"] = {
{name = "George", age = 20},
{name = "Pete", age = 25}
},
["Street 30"] = {
{name = "John", age = 32},
}
}
And I want to insert programmatically a third house, that is key "Street 35", with a person's details, Nick and 30 let's say. I am relatively new to lua and don't know how to do this, I must use table.insert but I am having troubles following the above format... Some help please?
Do it simple so:
house["Street 52"] = {{name = "Nick", age = 30}}
You could also mutate the third element of the houses table like this:
house[3]={name = "Nick", age = 30}
did you read this and get confused?
just try table.insert(house, {name = "Nick", age = 30}) and house[3] now contains the new element.
Related
I'm pretty new in lua and I have a problem that I've been trying to solve for several hours now.
So simply I have one table with 4 other tables (sry idk how it's named).
local myTable = {
player1 = {id = 1, points = 100},
player2 = {id = 3, points = 200},
player3 = {id = 4, points = 150},
player4 = {id = 7, points = 150}}
Id and points are random numbers.
All I want to do is get only 2 first tables from that table and use their values.
player1 = {id = 1, points = 100}
player2 = {id = 3, points = 200}
I would really appreciate your help, it's very tiring.
All I want to do is get only 2 first tables from that table and use
their values.
To get the inner tables just index myTable with the keys you've stored to inner tables at.
local table1 = myTable.player1
local table2 = myTable.player2
print("Player 1 has " .. table1.points .. " points")
How to get x first objects from table - lua
To answer this you would need to have a table with an order. Lua doesn't know the order of your table unless you have numerical keys.
If your table was like
local players = {
{id = 1, points = 100},
{id = 3, points = 200},
{id = 4, points = 150},
{id = 7, points = 150}}
You would simply pick players[1] and so forth to get the first x elements.
In your case you could do something like
myTable["player"..i] for i from 1 to x assuming that the keys represent the table order.
First you need is sort your table:
local myTable = {
{id = 1, points = 100},
{id = 3, points = 200},
{id = 4, points = 150},
{id = 7, points = 150}
}
You don't need to index those values as 'player1', 'player2', etc. So if you want the index(es) to appear as player1, etc. return the index and concatenated as player, like:
for key, value in pairs(myTable) do
print('player' .. key)
end
The past code will print all table indexes with prefix 'player'.
But to get only the first two values; what we can do? Simple! Make a function:
local myTable = {
{id = 1, points = 100},
{id = 3, points = 200},
{id = 4, points = 150},
{id = 7, points = 150}
}
local function collect(table, howMuch)
local response, index = {}, 1
for key, value in pairs(table) do
response[key] = howMuch and index <= howMuch and value or nil
index = index + 1
end
return response
end
local response = collect(myTable, 2)
print(response[1].id, response[2].id, response[3]) -- 1, 3, nil
What this function do?
Collect values from the first argument named table, and in base the second argument named howMuch (as a max of the response) return those values.
Or for friends: iters table myTable and only returning a table containing 2 fields.
So I have a dictionary:
local toFind = "Layla"
local songs = {
{name = "Eric Clapton - Layla", id = "123"},
{name = "Eric Clapton - I Shot The Sheriff", id = "321"}
}
Is it possible to use string.find(songs, toFind) or something similar to find the table that contains the "Layla" string?
All strings have string functions attached as methods.
Therefore you can directly do...
for k,v in pairs(songs) do
if v.name:find(toFind) then
return songs[k], v.name
end
end
...that returns the table and the full Text...
table: 0x565cbec0 Eric Clapton - Layla
how would I go about counting the number of times a string occurs in a table?
Basically I have a table that is like, say 200 entires for example (but it is larger)... each entry has a sub entry called name.
so..
itemlist[i].name == somestring.
Now I can search and find a match pretty easy using an if statment while looping though the table...
if string.find(string.lower(itemlist[i].name), string.lower(searchString)) ~= nil then
So say I'm searching for Thomas, it will return when it finds "Thomas F Malone".
The thing is some cases there are more than one result for the search value.. for example.. say there are three different names that all start with Thomas.
At the moment it will just find the 1st occurrence of the Thomas.
So the plan is to count all the occurrences of Thomas and then output all of them... but I can not work out how to get the numeric value of how many times the result is found in the table.
TL;DR - How can I count the number of occurrences that of a string in a table?
When you found the matching values, store them in a temporary table, e.g.
table.insert(temporaryTable, value)
rather than quitting the function using return. You can find below, a sample function which gathers and counts the occurence of a query string in a variable inside of a multidimensional table (or see it in action here).
--data
itemList = {
{name = "Denny Kuhlman", id = "6688"},
{name = "Russell Leisy", id = "3751"},
{name = "Hilario Stermer", id = "1886"},
{name = "Thomas Hemming", id = "9666"},
{name = "Samuel Lafuente", id = "8232"},
{name = "Lazaro Ashby", id = "5274"},
{name = "Ronnie Nicosia", id = "9664"},
{name = "Edison Seyal", id = "1344"},
{name = "Jerald Officer", id = "9497"},
{name = "Lupe Burdge", id = "266"},
{name = "Stephan Iler", id = "5968"},
{name = "Josue Stephens", id = "2128"},
{name = "Salvador Ortmann", id = "3643"},
{name = "Tony Ricker", id = "8799"},
{name = "Corey Carbone", id = "6485"},
{name = "Conrad Theberge", id = "139"},
{name = "Arnulfo Oquendo", id = "2861"},
{name = "Damien Balsley", id = "5572"},
{name = "Efren Sloop", id = "7106"},
{name = "Blair Clagon", id = "614"},
{name = "Dario Service", id = "1411"},
{name = "Paul Ashalintubbi", id = "3403"},
{name = "Felix Veal", id = "1539"},
{name = "Laurence Caskey", id = "2827"},
{name = "Will Ranallo", id = "8463"},
{name = "Thomas Brenner", id = "9599"},
{name = "Claudio Hallmark", id = "6265"},
{name = "Nolan Haslett", id = "9661"},
{name = "Lenard Pereira", id = "5652"},
{name = "Dusty Duer", id = "4034"},
}
--
function countStringOccurence(query, itemList)
query = string.lower(query)
--if query string is found, store index of the itemList in table searchResult
local searchResult = {}
for i, item in ipairs(itemList) do
local name = string.lower(item.name)
if string.find(name, query) then
table.insert(searchResult, i)
end
end
--return both the occurence count and the list of found item
return #searchResult, searchResult
end
--execute the function
count, foundItemList = countStringOccurence("thomas", itemList)
--print results
print(count) --> 2
for i, index in ipairs(foundItemList) do
print(index, itemList[index].name) --> 4 Thomas Hemming
--> 26 Thomas Brenner
end
NB: Please note that if your table/list entries might be moved around (e.g. sort), it might not be advisable to just store the array index because the references/values collected in foundItemList might become incorrect.
Just don't stop iterating over the table once you found something. Keep on going and increment a counter variable every time you find your string or put your results into a table and count its elements later.
local texts = {"a123", "b213", "a332", "d411", "a124"}
local result = {}
for i,v in ipairs(texts) do
if string.find(v, "a") then
table.insert(result, v)
end
end
print(#result)
I was wondering if some one can help me understand how Create Unique actually works in Neo4J. I am trying to register multiple addresses to a shipper node, where I expect the City, State and country to be same across the addresses so that they all point to the same node. However the issue is that the Create Unique is resulting in multiple instance of same node in the database.
Here is the function I have to register an address with the shipper which I call multiple times with same Shipper node, but different address pointing to same city.
public Node<Address> RegisterShipperAddress(Node<Shipper> shipper,AddressType addressType ,Address address, City city, State state, Country country)
{
var shipperRef = shipper.Reference;
var addressRef = neo4jClient.Cypher.Start(new { shipperNode = shipperRef }).CreateUnique("(shipperNode)-[r:HAS_ADDRESS { TypeName:{TypeName} }]->(addressRef{address})").WithParam("TypeName", addressType.TypeName).WithParam("address", address).Return<Node<Address>>("addressRef").Results.FirstOrDefault();
var cityRef = neo4jClient.Cypher.Start(new { addressNode = addressRef }).CreateUnique("(addressNode)-[:BELONGS_TO_CITY]->(cityRef{cityData})").WithParam("cityData", city).Return<Node<City>>("cityRef").Results.FirstOrDefault();
var stateRef = neo4jClient.Cypher.Start(new { cityNode = cityRef }).CreateUnique("(cityNode)-[:BELONGS_TO_STATE]->(stateRef{stateData})").WithParam("stateData", state).Return<Node<State>>("stateRef").Results.FirstOrDefault();
var countryRef = neo4jClient.Cypher.Start(new { stateNode = stateRef }).CreateUnique("(stateNode)-[:BELONGS_TO_COUNTRY]->(countryRef{stateData})").WithParam("stateData", state).Return<Node<Country>>("countryRef").Results.FirstOrDefault();
return addressRef;
}
Now suppose I call the the above method with different address as below:
//First Call....
RegisterShipperAddress(shipperNode,
new AddressType { TypeName = "REGISTRED" },
new Address
{
Address1 = "151/1 ABC Main",
Address2 = "My PO 1234",
Email = "abc#abc.com",
Mobile = "123456",
Phone = "123456"
},
new City { InternalId = 1, Label = "MyCity" },
new State { InternalId = 1, Label = "MyState" },
new Country { InternalId = 1, Label = "MyCountry" }
);
// Second call
RegisterShipperAddress(shipperNode,
new AddressType { TypeName = "BILLING" },
new Address
{
Address1 = "1 X Main Road",
Address2 = "PO 555",
Email = "abc#abc.com",
Mobile = "123456",
Phone = "123456"
},
new City { InternalId = 1, Label = "MyCity" },
new State { InternalId = 1, Label = "MyState" },
new Country { InternalId = 1, Label = "MyCountry" }
);
I end up with multiple instances of same node. Just wondering if its even possible to achieve this using the Create Unique clause of Cypher.
Here is the kind if graph I see..
--> (Address1)-->(MyCity)-->(MyState)-->(MyCountry)
(root) -->(Shipper) ||
--> (Address2)-->(MyCity)-->(MyState)-->(MyCountry)
Also whats the best way to create multiple nodes at once in one transaction, I think in the above code, each nodes are created in a separate Transactions.
CREATE UNIQUE in Cypher 1.9 is not encouraged.Please, if you can, use Neo4j 2.0.0.M05 ++ and create a unique constraint on Cities, States and Countries, see http://docs.neo4j.org/chunked/snapshot/query-constraints.html#constraints-create-uniqueness-constraint and then MERGE the city node, the create the address. Here a graphgist example:
http://gist.neo4j.org/?6549962
I have a table in lua with some data.
sometable = {
{name = "bob", something = "foo"},
{name = "greg", something = "bar"}
}
I then want to loop through the table and assign a number to each name as a variable. New to lua and tried it like this.
for i,t in ipairs(sometable) do
t.name = i
end
I was then assuming print("name1", bob) would give me name1 = 1. Right now I'm getting nil. So I'm back to my ugly static list of variables till some kind soul tells me how I'm an idiot.
> sometable = {{name = "bob", something = "foo"},{name = "greg", something = "bar"}}
> for i,t in ipairs(sometable) do t[t.name] = i end
> for i,t in ipairs(sometable) do for j,u in pairs (t) do print (j,u) end end
name bob
something foo
bob 1
greg 2
something bar
name greg
> return sometable[1].bob
1>
The ipairs function will iterate only through numerically indexed tables in ascending order.
What you want to use is the pairs function. It will iterate over every key in the table, no matter what type it is.