Finding the Value of an Object Element within an Array - arrays

I have a table that im inserting into , The table holds Plate Values
How would i go about iterating over the table to return the following as true
function table.contains(table, element)
for _, value in pairs(table) do
if value == element then
return true
end
end
return false
end
My current table insert
for k, v in pairs(returnVehicleData) do
platesAvailable = v.plate
newTable = {['plate'] = platesAvailable}
table.insert(vehiclePlateTable, newTable)
end
The data thats being returned
[{"plate":"47QVS009"},{"plate":"86KIE632"}]
I want to check the subsequent value after the : on both objects.

I ended up doing this and getting it to work
newValueTable = {}
for Key = 1, #tabledPlate, 1 do
table.insert(newValueTable, tabledPlate[Key].plate)
end
Because the elements are part of an even bigger table of data , they dont actually return as a string. But thank you for the suggestion Coordinate Newton

Related

How can I loop through a vector data with attribute table so that I create a new field by appending values from an existing field?

See how the attribute table should be if the algorithm worksHow can I loop through vector data with an attribute table so that I create a new field by appending values from an already existing field in the vector data? So the logic I want to have is this:
I want that when I run the script, a search for the expression “Out” is done in the field index with the name “fa_to”. If found, the corresponding row value in the ‘fa_id is then inserted into the newly created field named ‘Bury_ID. It does this until it exhausts the entire row value for ‘fa_to.
My Code:
fn = ‘C:/PLUGINS1/p3/now3.shp’
tile_layer_used = iface.addVectorLayer(fn, ”, ‘ogr’)
fc = tile_layer_used.featureCount()
fa_to = tile_layer_used.fields().indexFromName(‘Tile_TO’) #field has all integers and a row named ‘Out’
fa_id = tile_layer_used.fields().indexFromName(‘Tile_ID’) #field id with numbers 1 to 50
# fa_to Tally with the fa_id
my_field_name = ‘Bury_ID’
tileorder = {}
with edit(tile_layer_used):
tile_layer_used.addAttribute(QgsField(my_field_name, QVariant.String, len=5, prec=0))
tile_layer_used.updateFields()
for f in tile_layer_used.getFeatures():
if fa_to == “Out”:
tileorder = fa_id
else:
tileorder = fa_id
f[my_field_name] = tileorder
tile_layer_used.updateFeature(f)
my output creates the new field named ‘Bury_ID’ but only has a single number all through instead of the corresponding field ids from ‘fa_id’.

Table[1] returning nil when table does exist and has values

local mapSpawnsData = {}
local JSONData = file.Read(filePath) -- read file as json text
mapSpawnsData = util.JSONToTable(JSONData) -- convert JSON to table
print("TABLE:")
PrintTable(mapSpawnsData)
print("TABLE[1]:")
print(tostring(mapSpawnsData[1]))
This is a script for a game called garrysmod. PrintTable() is a function I can call included in the game.
The code snippet I included returns this: (Same output if I remove the tosring())
TABLE:
gm_construct:
1 = -1303.524902 167.472397 -44.081600
2 = 1250.890137 331.746185 -44.081600
3 = 674.012085 223.775604 -32.148102
TABLE[1]:
nil
I expected to get back "gm_construct". What am I missing here?
What you didn't notice is that PrintTable printed gm_construct: first and then 1 = .
That means the table actually contains only gm_construct key with a table with 3 keys.
To be able to always read PrintTable output properly look at the ident. 1 = is tabulated to the right once, this means they are keys of something nested in the table you initially printed.
If this still confuses you, try to run this:
for k,v in pairs(mapSpawnsData) do
print(k, "=", v)
end
This won't print nested content.
To make your code work do mapSpawnsData.gm_construct[1] or mapSpawnsData["gm_construct"][1]

LUA script: Nested loop inserts only last item

I have two loops, a main loop and a sub-loop inside the main loop. Both loops populate the same table (and sub-table). But for some reason the sub-loop only stores the last added item in the nested table.
For instance, main group 1 has sub-groups stored as 1-9:
printTable(data[1][subItems][1]) -- returns error (index nil value)
printTable(data[1][subItems][9]) -- dumps table to console
If I break the sub-loop after one iteration then data[1][subItems][1] contains data
for i=startId, endId, 10 do
items = loadItems(i)
data[i] = {['items'] = items}
for x=i+1, i+10-1 do
subItems = loadItems(x)
print('adding items to sub-group: '..x..' for main group: '..i)
data[i]['subItems'] = {}
data[i]['subItems'][x] = {['items'] = subItems}
end
end
end
Since I'm printing some debug info inside the sub-loop, I know that, the code is being executed. And I know that loadItems(x) is getting the data on each iteration, because if i dump the loadItems(x) to console in the sub-loop, all is there on each iteration.
What is this wizardry?
Silly me, how could I miss it!
The answer is of course to move the data[i][subItems] = {} outside the sub-loop:
for i=startId, endId, 10 do
items = loadItems(i)
data[i] = {['items'] = items}
data[i]['subItems'] = {} <----------------------------------------------
for x=i+1, i+10-1 do
subItems = loadItems(x)
print('adding items to sub-group: '..x..' for main group: '..i)
data[i]['subItems'][x] = {['items'] = subItems}
end
end
end

How to index a table automatically and loop it in ipairs while keeping all data?

Table:
localization_strings = {
string_1 = "Text Here",
string_2 = "Some More Text Here",
string_3 = "More Text"
}
This is obviously not the whole table, but just a small sample. The real table is over 500+ lines. The reason I don't just redo the table is because other functions reference it and I don't have access to those files to fix them, so I have to find a work around. Also, because it would quite tedious work and can cause problems with other codes.
I have made 2 attempts at solving this problem, but I can only get one of the values I want (incorrect terminology, I think) and I need both as 1 is display text and 1 is data for a function call.
Attempts:
-- Attempt #1
-- Gives me the string_#'s but not the "Text"...which I need, as I want to display the text via another function
LocalizationUnorderedOpts = {}
LocalizationOpts = {}
for n,unordered_names in pairs(localization_strings) do
if (unordered_names) then
table.insert( LocalizationUnorderedOpts, n)
end
end
io.write(tostring(LocalizationUnorderedOpts) .. "\n")
table.sort(LocalizationUnorderedOpts)
for i,n in ipairs(LocalizationUnorderedOpts) do
if (n) then
io.write(tostring(i))
table.insert( LocalizationOpts, { text = tostring(LocalizationUnorderedOpts[i]), callback = function_pointer_does_not_matter, data = i } )
end
end
-- Attempt #2
-- Gives me the "Text" but not the string_#'s...which I need to as data to the callback to another function (via function pointer)
LocalizationUnorderedOpts = {}
LocalizationOpts = {}
for n,unordered_names in pairs(localization_strings) do
if (unordered_names) then
table.insert( LocalizationUnorderedOpts, localization_strings[n])
end
end
io.write(tostring(LocalizationUnorderedOpts) .. "\n")
table.sort(LocalizationUnorderedOpts)
for i,n in ipairs(LocalizationUnorderedOpts) do
if (n) then
io.write(tostring(i))
table.insert( LocalizationOpts, { text = tostring(LocalizationUnorderedOpts[i]), callback = function_pointer_does_not_matter, data = i } )
end
end
If I understand it correctly, you need to sort the non-array table. Your first attempt has done most of the work: build another table, which has the values the same as the keys in the original table.
What's left is how to get the original values like "Text Here", for that you need to index the original table:
for k, v in ipairs(LocalizationUnorderedOpts) do
print(v) --original key
print(localization_strings[v]) --original value
end

Lua - check if array exists

I'm trying to find out if a certain array exists via an if statement such as
if array{} == nil then array = {} else print("it exists") end
The above doesn't work it seems and I have no way of checking if it exists, basically I'm creating an AddOn which scans a log for a certain event and if it's true it returns the spellName. I wish to create an array with that spellName, however spellName = {} doesn't work as it seems to just create a new array (rather than updating the existing one).
local _SPD = CreateFrame("Frame");
_SPD:RegisterEvent("COMBAT_LOG_EVENT_UNFILTERED");
_SPD:SetScript("OnEvent", function(self, event, ...)
local timestamp, type, sourceName = select(1, ...), select(2, ...), select(5, ...)
if (event == "COMBAT_LOG_EVENT_UNFILTERED") then
if select(2,...) == "SPELL_AURA_APPLIED" then
if select(5,...) == UnitName("player") then
local spellID, spellName = select(12, ...), select(13, ...)
spellName = {
sourceName = {
}
}
table.insert(spellName["sourceName"], {id = spellID, stamp = timestamp })
for k,v in pairs ( spellName["sourceName"] ) do
print (k.. ": " ..v["id"].. " at " ..v["stamp"])
end
end
end
end
end);
Basically it's just re-creating the table every time a certain aura is applied on me (which is expected behavior)
I've banged my head but I have no idea how to check if spellName (and sourceName) exists and if so do not create them again since in this case the variable already exists because it returns the value to me so I can't check if they're nil as they won't be, I need to somehow check if a table exists on those values and if not create them.
Thanks in advance.
Your declaration for table checking is wrong. Use it like this:
if type(array) == "table" then
print("it exists")
else
array = {}
end
Try this:
local spellID, spellName = select(12, ...), select(13, ...)
spellName = spellName or {}
spellName.sourceName = spellName.sourceName or {}
table.insert(spellName.sourceName, {id = spellID, stamp = timestamp })

Resources