Modifies the key but doesn't actually modify the value? - arrays

players={}
players["foo"] =
{
wins = 0, deaths = 0, draws = 0, rounds = 0, bet = "None", rank = 0
}
modify = function (stat, set, target)
local player = players[target]
local dictionary =
{
["wins"] = player.wins, ["deaths"] = player.deaths,
["draws"] = player.draws, ["rounds"] = player.rounds,
["bet"] = player.bet, ["rank"] = player.rank,
}
if dictionary[stat] then
dictionary[stat] = set
print(dictionary[stat])
print(player.wins)
end
end
modify("wins", 1, "foo")
The code mentioned above doesn't really function as it's supposed to. It modifies the key "wins" but the value it's self (player[target].wins) isn't modified.

Numeric values aren't references. You get copies when you copy them not references back to their original locations.
So when you assign ["wins"] = player.wins you aren't getting a reference to the wins field in the player table. You are copying the value into the dictionary table.
If you want to modify the player table you need to modify the player table.
Also the indirection in that function is entirely unnecessary. You can reference player[stat] just the same as you can reference dictionary[stat].
tbl.stat is syntactic sugar[1] for tbl["stat"].
Additionally, as seen in ยง2.5.7 of the lua manual:
tbl = {
stat = 0,
}
is the same as
tbl = {
["stat"] = 0,
}
when the name is a string, does not start with a number, and is not a reserved token.
[1] See the The type table paragraph.

Related

How to get next id for ID generation strategy = GenerationType.TABLE

Is there an easy way to get the next id of an object which use id generation strategy GenerationType.TABLE and a custom database table? My problem is that allocation size is not 1 (which is fine - optimization), but this way JPA doesn't update the sequence table on every object creation. So I'm wondering is there a way to hit next sequence ( I need it for different operation) and next time new object is created it should use next sequence as well. So id which I will use for different purpose will be skipped next time a new object is created.
Example of the mapping:
#Id
#GeneratedValue(strategy = GenerationType.TABLE, generator = "TestIdGenerator")
#GenericGenerator(
name = "TestIdGenerator",
strategy = "enhanced-table",
parameters = {
#Parameter(name = "table_name", value = "sequences"),
#Parameter(name = "segment_column_name", value = "key_column_txt"),
#Parameter(name = "segment_value", value = "test_id"),
#Parameter(name = "value_column_name", value = "next_id"),
#Parameter(name = "increment_size", value = "20"),
#Parameter(name = "optimizer", value = "pooled-lo")
}
)
#Column(name = "test_id")
#EqualsAndHashCode.Include
#ToString.Include
private Integer id;
I'm using SequenceStyleGenerator (Hibernate 5).
How about just invoking the same code that Hibernate does? Something like this:
Integer nextValue = (Integer) session.getSessionFactory()
.unwrap(SessionFactoryImplementor.class)
.getRuntimeMetamodels()
.getMappingMetamodel()
.findEntityDescriptor(MyEntity.class)
.getIdentifierGenerator()
.generate(session, null)

Cannot get first item of array

Here's an array printed by a function getTargets();:
{
name = {
isPlayer = true,
isBlocking = false,
username = "yes"
}
}
When I do players = getTargets(); to put this in variable and want to access first variable no matter its name, I have some trouble. I tried those:
players.name.username --displays "yes"
players[0].username --displays nil
players[1].username --displays nil
I want to access first variable of this array no matter what is its value.
How can I do this?
Your code
local players = {
name = {
isPlayer = true,
isBlocking = false,
username = "yes"
}
}
is equivalent to
local players = {}
players.name = {
isPlayer = true,
isBlocking = false,
username = "yes"
}
So there is no index 0 or 1, hence players[0] and players[1] are nil.
players[0].username and players[1].username will cause an error for indexing nil values.
To get the first element of a table of unknown keys simply do this:
local key, value = next(someTable)
https://www.lua.org/manual/5.3/manual.html#pdf-next
When called with nil as its second argument, next returns an initial
index and its associated value.
Keep in mind that:
The order in which the indices are enumerated is not specified, even
for numeric indices.
If you want to make sure you should change your data structures accordingly.
But I cannot give you much advice here as I don't know the purpose of this.
You could have a little function like (simplyfied):
local function addPlayerToList(playerList, playerLookUpTable, player)
table.insert(playerList, player)
playerLookUpTable[player.name] = #playerList
end
Read something about OOP in Lua for nicer and more advanced ideas.
You can try to get the key/name in this way:
local players = {
name = {
isPlayer = true,
isBlocking = false,
username = "yes"
}
}
local FirstPlayer
for k,v in pairs(players) do FirstPlayer=k break end
print(players[FirstPlayer].username)
however there is no guarantee that this will always be the first. But maybe this is your case.
You don't even need a for loop:
n,t = pairs(players)
firstKey, firstValue = n(t)
https://repl.it/JBw1/1
As lhf pointed out, you don't even need pairs, you can simply do
firstKey, firstValue = next(players)

Lua Array Deep Array search for Open Tibia Script

Looking to get info from an array inside an array, without having exact info basically.
local cfg_raids = {
[2] =
{
["10:17"] = {
raidName = "Rats - Thais",
Event_Type = "Raid Activated",
Storage = 1234,
alreadyExecuted = false
},
["10:20"] = {
raidName = "Testing this shit",
Event_Type = "Raid Activated",
Storage = 1235,
alreadyExecuted = false
},
},
[3] =
{
["12:00"] = {
raidName = "OrcsThais",
Event_Type = "Raid Activated",
Storage = 1236,
alreadyExecuted = false
},
},
Trying to Grab the time randomly without actually having the exact time stamp.
So like when the script activates the timestamp array ["10:17"] it grabs all the next arrays info ["10:20"] without actually knowing the ["10:20"]
OPEN TIBIA INFORMATION: http://otland.net/threads/looking-for-some-assistance-on-a-script.216303/
With non-integer keys like that you can't really do it. You can try using the next function to get the next key from your current key but you have no guarantees which next key you will get if there are more than two keys in the table (you can not even guarantee that it will be consistently the same next key).
You could use integer indices in that table and make time a field of the table and then simply use the next integer as your next key if that works however.
You could also store the times used as keys, in whatever order you want, in the integer indices in the table (or some other table) and use that without needing to redo the table itself (e.g. cfg_raids = { [2] = { "10:17", "10:20", ["10:17"] = {...}, ["10:20"] = {...} } }).

Apex Lookup Value copy to second Object

I have a trigger that moves the values from one object to another, but am stuck on how to move the values of the lookup fields from one to the other. what is the syntax? If you could show me the Company and the Chair_Rep ones that would be great!
<Lead> newLeadsList= new List<Lead>();
for (integer i=0; i<newContacts.size(); i++) {
if (newContacts[i].createlead__c == TRUE && oldContacts[i].createlead__c == FALSE ) {
newLeadsList.add(new Lead(
firstName = newContacts[i].firstName,
lastName = newContacts[i].lastName,
***Company = newContacts[i].account.name,***
Status = 'identified',
LeadSource = newContacts[i].leadsource ,
Product_Interest__c = 'CE',
//ContactLink__c = newContacts[i].ID,
Title = newContacts[i].title,
Email = newContacts[i].email,
//***Chair_Rep__c = newContacts[i].Chair_Rep__c***
Phone = newContacts[i].Phone,
MobilePhone = newContacts[i].MobilePhone,
// Address = newContacts[i].MailingAddress,
//Website = newContacts[i].Website,
nickname__c = newContacts[i].Nickname__c
Lookup fields should contain references (IDs) on records.
Is 'Company' a standard Lead field in your code?
***Company = newContacts[i].account.name,***
If so, then it's a Text(255) type field, which cannot be used as lookup.
If you need to make a lookup on a Contact's account record, then you can create a custom Lookup field on Lead with reference to Account. And then you could try this code (assuming ContactCompany is that custom lookup field :
ContactCompany__c = newContacts[i].AccountId
or
ContactCompany__c = newContacts[i].Account.Id
Chair_Rep__c and newContacts.Chair_Rep__c should be lookup fields on same object. Then this
Chair_Rep__c = newContacts[i].Chair_Rep__c
or this should work
Chair_Rep__c = newContacts[i].Chair_Rep__r.Id

Stopping physics body from movement in Corona SDK

I'm learning Corona SDK and I'm making small project in that purpose.
So, my problem is next one:
I managed to create 2 physics objects and make one of them "explode" when it collides with the other one. My question is how to make other object (it has linear impulse applied) stop when it collides? Also, when it stops, it has to be removed from the screen to avoid colliding with other objects...
Here is a part with removing first object on collision:
nloDrop = function()
local nlo = display.newImageRect("nlo.png", 65, 25)
nlo.x = 35 + mRand(410) ; nlo.y = -60
physics.addBody(nlo, "dynamic", {density=1, bounce = 0, friction = 0, filter = {maskBits = 4, categoryBits = 2}})
nlo:applyLinearImpulse(0, 0.8, nlo.x, nlo.y)
nlo.isSensor = true
nlo.collision = nloCollision
nlo:addEventListener("collision", nlo)
nlo.name = "nlo"
toFront()
end
And here is 'collision' function:
function nloCollision(self, event)
if ((event.other.myName == "weaponName") then
print("funkc")
self:removeSelf()
self:removeEventListener("collision", nlo)
self = nil
if weapon ~= nil then
-- stop moving of weapon
end
end
end
Thanks!
You can make the object bodyActive false and then it will not respond to physics. You cant remove a body from physics within the active screen so its a better option to keep that object out of the screen.
I made it setting the object like local variable and making a function that deletes/removes each variable (object) after some interaction or collision.
1st function contains object creating (that is a local type under function) and applying physics to that object.
2nd function contains deleting (self:removeSelf()) that works because each object is object for itself and when deleting it, physics stuff will continue to work because new local object is going to be created.
function create(event)
local weap1 = display.newImage("weap1.png", 0, 0)
weap1.x = turret.x ; weap1.y = turret.y
weap1.rotation = turret.rotation
weap1.collision = weap1Collision
weap1:addEventListener("collision", weap1)
physics.addBody(weap1, "dynamic", {density = 1, friction = 0, bounce = 0, filter = {maskBits = 2, categoryBits = 4}})
weap1:applyLinearImpulse(forceWeap1*xComp, forceWeap1*yComp, weap1.x, weap1.y)
function weap1Collision(self,event)
if (event.other.name == "collisionObject") then
self:removeSelf()
self:removeEventListener("collision", weap1)
self = nil
end
end
local type of variable (object) makes it work.
P.S.: vanshika, thanks for your answer, it's useful ;)

Resources