Iterate through LUA Table for string match - scripting

I'm trying to match two tables by string case in sensitive.
Example
[6] =
{
["itemName"] = [Ore],
["cleanName"] = [[Iron Ingot]],
["secs"] = 25004,
["gN"] = [[Luminary]],
["buyer"] = [[#Naptha42]],
["eventType"] = 15,
["timestampz"] = 1399514069,
["quantity"] = 100,
["soldAmount"] = 500,
["seller"] = [[#FataI]],
},
I'm trying to move items from the above table format into a new table, or filter them into a list.
g = e.cleanName
for k, v in pairs(savedTable.ALL_ITEMS) do searchTable[k] = v
if g == savedTable.ALL_ITEMS.cleanName then
table.insert(searchTable, savedTable.ALL_ITEMS)
end
end
The problem above is g never = that savedTable.
The table has a few thousand entries and I'm trying to display by search, I believe the best way is to create a new table with the values im looking for?
Or is there a way to use the string.match to iterate through the table and display (print) only these values.
//Update
I have an active search, each time the user enters a letter it will search the table.
Example.
Val1 = "Hello"
Val2 = "Goodbye"
Val3 = "Hi"
While searching and the user enters "H" or "h" I want the results for "hello, hi" to show up but not "goodbye"
so with the if g == string.match(savedTable.ALL_ITEMS.cleanName)
not sure if that is correct.
//UPDATE for solution of what worked (thanks ESOUI)
local searchForItem = string.lower(g)
for k, v in ipairs(myTable.ALL_SALES) do
-- if string.lower(g) == string.lower(v.cleanName) then
if string.lower(v.cleanName):find(searchForItem) then
if v.cleanName ~= nil then
table.insert(searchTable, v)
end
end
end

If ALL_ITEMS is a table that contains tables then it isn't ever going to have a cleanName field directly.
Is that == in the loop intended to be against v?
Also, if ALL_ITEMS is integer indexed you probably want ipairs instead of pairs to walk the table in order.
Why are you inserting every element into searchTable (via searchTable[k] = v) and then also attempting to insert the matching entries again (via table.insert)?
You can use string.match to match g against the cleanName in your loop if you need to but that isn't going to solve the problem if you aren't comparing what you think you are comparing.

Related

Variable that depends on another variable VBA

I have an interesting question about referencing another variable based on another variable in an array.
Below is my code:
Dim company, price, sdev, mean, random
Dim companies
companies = Array("mm", "tgt", "boog")
mm_price = 0
mm_mean = 0
mm_sdev = 0
tgt_price = 0
tgt_mean = 0
tgt_sdev = 0
boog_price = 0
boog_mean = 0
boog_sdev = 0
For i = 1 To 3
company = companies(i)
mean = company & "_mean"
sdev = company & "_sdev"
Next i
Now, the issue occurs when I attempt to define the "mean" and "sdev" variables, as they will not use the "0" value, but instead give it the string name "mm_mean" etc. mm_mean = 0, therefore, I want mean = 0 when i = 1. Clear?
Thanks, and let me know. It is a rather strange question, and the code is cut from many different functions, so if it doesn't make sense as to why I am doing this, my apologies. I tried to make it as simple as possible so it wouldn't confuse the answerer.
This is a good example of when custom data-structures (aka "record types", "structs") should be used to group related data together. In VBA the syntax is Type:
Type Company
Name As String
Price As Currency
Mean As Double
SDev As Double
End Type
Public Sub CalculateCompanyInfo()
Dim companies(3) As Company
companies(0).Name = "mm"
companies(0).Price = 123
companies(1).Name = "tgt"
companies(1).Price = 456
companies(2).Name = "boog"
companies(2).Price = 789
For i As Integer = 0 to UBound(companies)
companies(i).Mean = ...
companies(i).SDev = ...
Next i
End Sub
Where ... means whatever custom calculation you need to do to get that value.

ERROR: make sure that the index is less than the size of the collection

When I select/click the first 2 rows individually, I am fine. I get an error if I select/click any row after that. The error message is:
" Index was out of range. Must be non-negative and less than the size of the collection"
I added a RowIndexCount to count how many rows the application is reading, and it returns 84. What is possible wrong with it?
VB.NET
Dim rowDGVDataPhys As Integer = DGVDataPhys.CurrentCell.RowIndex
txtRowIndex.text = rowDGVDataPhys
DGVDataPhys.Rows(rowDGVDataPhys).Selected = True
DGVData.Enabled = True
DGVDataPhys.Enabled = True
Dim CountRowIndexes As Integer = 0
CountRowIndexes = DGVDataPhys.RowCount
'To capture how many total rows in the GRID.
MsgBox(CountRowIndexes) 'I found 84 rows
vDeptID = DGVDataPhys.Rows(DGVDataPhys.SelectedCells(rowDGVDataPhys).RowIndex.ToString()).Cells("DeptKey").Value
vDeptName = DGVDataPhys.Rows(DGVDataPhys.SelectedCells(rowDGVDataPhys).RowIndex.ToString()).Cells("DeptName").Value
You are indexing row using the SelectedCells collection, not the Current cells Row index...
Do this instead
vDeptID = DGVDataPhys.Rows(rowDGVDataPhys).Cells("DeptKey").Value
vDeptName = DGVDataPhys.Rows(rowDGVDataPhys).Cells("DeptName").Value

Poker Hand evaluation through LINQ

I am creating a poker game - Texas Holdem (5 cards on the table and 2 cards for myself).
I've already created flush, straight and straight flush functions and I got stuck on evaluating if the hand has a:
1. Four of a kind
2. Three of a kind
3. Full house
4. Two pairs
5. One pair
I believe I can write one function for all of the above, that will return a corresponding string.
I have created a list that holds list of Cards (7 cards)
Class Card has a property cardNumber of Integer type (Ace = 1, Two = 2, Three = 3 etc)
Here is my function:
Public Shared Function ofAKind(hand As List(Of Card)) As String
Dim result As String = ""
Dim counter As Integer
Dim IntegerList As New List(Of Integer)
'creating a list of integers that are representing faces of cards
Do
IntegerList.Add(hand.Item(counter).cardNumber)
counter += 1
Loop Until counter = hand.Count
Dim groupedIntegers = From Int In IntegerList
Group By Int
Into grouping = Group, Count()
'and here is my problem: how can I make such a grouping? below is just pseudocode.
'When using a debugger, I see that it groups them well. It is just that I do not know
'how to use LINQ to extract that grouping into the below if statement and get a corresponding string.
'if grouping = 4 Then
'result = "Four of a kind"
'if grouping = 3 andAlso grouping = 2 Then
'result = "Full House"
'if grouping = 2 andAlso grouping = 2 Then
'result = "Two Pairs"
'if grouping = 2 Then
'result = "Pair"
Return result
End Function
For the lack of being able to comment.
Possibly String.Concat all of the card Values together (with whitespace in-between each) and use a Regex.Matches(...) with match code "\d" to match the Numbers
Then Array.ForEach(...) for the Groups() with an in-line If[...] to count the occurrences in each group and test if it has particular combinations of matches.
It may be a little tedious, and a long in-line Linq, but just a thought :p
I figured it out. I am sure it can be done in a cleaner way, but it worked for me. At this phase of my programming discovery - this is a next milestone achieved. Thanks to Plutonix. Appreciate it.
Public Function ofAKind(IntegerList As List(Of Integer)) As String
Dim result As String = "YES"
Dim groupedIntegerList As New List(Of Integer)
Dim groupedIntegers = From Int In IntegerList
Group By Int
Into LOL = Group, Count()
'creating another list (I am sure there is a cleaner way, but I don't know it yet)
For Each e In groupedIntegers
groupedIntegerList.Add(e.Count)
Next
If groupedIntegerList.Contains(3) And groupedIntegerList.Contains(2) Then
result = "Fullhouse!"
ElseIf groupedIntegerList.Contains(4) Then
result = "Four of a kind!"
ElseIf groupedIntegerList.Contains(3) Then
result = "Three of a kind"
ElseIf groupedIntegerList.Contains(2) Then
result = "Pair!"
End If
'ugly way to search for two pairs (but it works)
If result = "Pair!" Then
Dim searchingForTwoPairs = From int In groupedIntegerList
Where int > 1
Group By int
Into LOL2 = Group, Count()
Dim twoPairsList As New List(Of Integer)
For Each e In searchingForTwoPairs
twoPairsList.Add(e.Count)
Next
If twoPairsList.Contains(2) Or twoPairsList.Contains(3) Then
result = "Two pairs!"
End If
End If
Return result
End Function

issues with entering variables into dictionary

here's my code, or rather the part of the code i'm having issues with.
the problem is at the if expression, where i'm trying to check whether a value is already in a dictionary (the actual code is in a larger while loop, used for a user interface), but when it runs the second time round it will always go into the else section, i'm assuming because of the variable name already being present in the dictionary.
Dict1 = {#empty dictionary}
completedList = (#list variable containing “true” and “false”)
name = input(“enter your name”)
score = completedList.count("true")
callback = 'cont'
while callback == 'cont':
if name not in dict1 == True:
dict1 = [name] = score
callback = ""
else:
print("that name is already in use \n please choose another")
name = input("enter a name")
I'm a student, so the simpler the code the better.
dict1 = {'er'}
completedLis=()
name = input("enter your name")
score = completedLis.count("true")
callback = 'cont'
while (callback == 'cont'):
if (name not in dict1):
dict1 = name = score
callback = ''
else:
print("that name is already in use \n please choose another")
name = input("enter a name")
I hope this solves ur problem if u type er(dict1='er')it will go to else or if u type anything else it will work

Lua Script Pattern Matching Problem

First of all, I have been using this site as a reference through the entire scripting process and it has been wonderful. I appreciate how useful and knowledgeable everyone is here. With that in mind, I have a question regarding matching (pattern matching) in Lua. I am writing a script that essentially takes input from a file and imports it into a table. I am checking for specific MAC addresses in the file as the host I am querying.
if macFile then
local file = io.open(macFile)
if file then
for line in file:lines() do
local f = line
i, j = string.find ( f, "%x+" )
m = string.sub(f, i, j)
table.insert( macTable, m )
end
file:close()
end
This parses the file into a format I will use to query later. Once the table is built, I run a pattern matching sequence to try and match the MAC from the table by iterating the table and matching the pattern against the current iteration:
local output = {}
t = "00:00:00:00:00:00"
s = string.gsub( t, ":", "")
for key,value in next,macTable,nil do
a, p = string.find ( s, value )
matchFound = string.sub(s, a, p)
table.insert( output, matchFound )
end
This doesn't return any output although when I enter it line by line in a Lua prompt, it seems to work. The variables are being passed correctly I believe. Any suggestions?
If your macFile uses a structure like this:
012345678900
008967452301
000000000000
ffffffffffff
The following script should work:
macFile = "./macFile.txt"
macTable = {}
if macFile then
local hFile = io.open(macFile, "r")
if hFile then
for line in hFile:lines() do
local _,_, sMac = line:find("^(%x+)")
if sMac then
print("Mac address matched: "..sMac)
table.insert(macTable, sMac)
end
end
hFile:close()
end
end
local output = {}
t = "00:00:00:00:00:00"
s = string.gsub( t, ":", "")
for k,v in ipairs(macTable) do
if s == v then
print("Matched macTable address: "..v)
table.insert(output, v)
end
end
I am just leaving from work and can't have a deeper look at your problem right now, but the next two lines seem quite odd.
t = "00:00:00:00:00:00"
s = string.gsub( t, ":", "")
Basically you are removing all the ':' characters in the string t. Afterwards you end up with s being "000000000000". This is probably not what you want?