creating variables using for loop in Lua - for-loop

Im trying to create variables like these using a for loop..
TPidL1 = Load('TPidL1', '')
TPidL2 = Load('TPidL2', '')
TPidL3 = Load('TPidL3', '')
TPidL4 = Load('TPidL4', '')
TPidL5 = Load('TPidL5', '')
After reading other posts, I tried this but no luck
for z = 1, 5, 1 do
"TPidL"..z = Load('TPidL'..tostring(z), '')
end
Any ideas how I could approach this better?
thanks

Just use a regular table instead of messing with globals..?
TPidLs = {}
for z = 1, 5, 1 do
TPidLs[z] = Load('TPidL' .. tostring(z), '')
end

you can do this via the global namespace _G:
for z = 1, 5 do
_G["TPidL"..z] = "TPidL"..z
end
print(TPidL1,TPidL2,TPidL3,TPidL4,TPidL5)

Well, AFAIK it's not possible directly, but Lua being quite flexible, there is a way. The key thing is to understand that all the global variables and functions are simply stored in a simple Lua table named _ENV. A simple example to highlight this:
MyVariable = "Hello"
for Key, Value in pairs(_ENV) do
print(Key,Value)
end
This code will show something like this:
loadfile function: 0000000065b9d5a0
os table: 0000000000e19f20
collectgarbage function: 0000000065b9d0a0
io table: 0000000000e18630
error function: 0000000065b9d020
_VERSION Lua 5.4
_G table: 0000000000e11890
print function: 0000000065b9cd60
warn function: 0000000065b9ccc0
arg table: 0000000000e19ba0
table table: 0000000000e18c50
type function: 0000000065b9c780
next function: 0000000065b9cea0
ipairs function: 0000000065b9ce50
assert function: 0000000065b9d6f0
debug table: 0000000000e19f60
rawget function: 0000000065b9cbc0
load function: 0000000065b9d4a0
coroutine table: 0000000000e18c90
pairs function: 0000000065b9d380
string table: 0000000000e19a20
select function: 0000000065b9c890
tostring function: 0000000065b9c860
math table: 0000000000e19a60
setmetatable function: 0000000065b9d2d0
MyVariable 1
dofile function: 0000000065b9d670
utf8 table: 0000000000e19d20
rawequal function: 0000000065b9cc70
pcall function: 0000000065b9c7e0
tonumber function: 0000000065b9c930
rawlen function: 0000000065b9cc10
xpcall function: 0000000065b9c6e0
require function: 0000000000e177c0
package table: 0000000000e17840
rawset function: 0000000065b9cb60
getmetatable function: 0000000065b9d610
That's it: _ENV is simple table which make the link between the function name and its implementation and between variable name and its value. Regarding you question, I have absolutely no idea what is the definition of the Load function.
But if you want to generate variable names dynamically, you could try:
for Index = 1, 5 do
_ENV["MyVariable"..Index] = Index
end
print(MyVariable1)
print(MyVariable2)
print(MyVariable3)
print(MyVariable4)
print(MyVariable5)
It should print:
> print(MyVariable1)
1
> print(MyVariable2)
2
> print(MyVariable3)
3
> print(MyVariable4)
4
> print(MyVariable5)
5
>

Related

'Return' outside of function

def suspect_dict():
dict = pd.read_csv("suspectdict.csv", squeeze=True)
pattern = '|'.join(dict)
result = np.where(news_df["headline"].str.contains(pattern, na=False),1, 0)
for index, value in enumerate(result):
return {value}
I am trying to return 1 and 0 if words in "suspectdict" exists in "news_df".
Code works for
for index, value in enumerate(result):
print(f"{value}")
example of output:
0
1
0
1
1
When using return I got Syntax error: 'return' outside function
How do I fix this?
As the error says, your return is outside a function. Return should be used within a scope of a function, in your case, on suspect_dict() function.
You could either just loop the result and print it, without returning anything, also, you don't need to use enumerate as you're not dealing with indexes:
def suspect_dict():
dict = pd.read_csv("suspectdict.csv", squeeze=True)
pattern = '|'.join(dict)
result = np.where(news_df["headline"].str.contains(pattern, na=False),1, 0)
for value in result:
print(value)
But if you need to return the result, you could just use return result inside the function:
def suspect_dict():
dict = pd.read_csv("suspectdict.csv", squeeze=True)
pattern = '|'.join(dict)
result = np.where(news_df["headline"].str.contains(pattern,na=False),1,0)
return result
Note that python uses indentation to understand where a block of code begins and ends, so make sure that all codes that might belong to the function are well indented.

store each loop value in a table lua

Is there a way to store the loop result in a table in lua?
I tried the following but it does not work
Name = "x-"
tabl = {}
for i =1, 5 do
tabl = {i}
end
print (tabl[1])
These questions are due to lack of basic syntax understading, I would highly recommend reading this tutorial: Lua Tutorial
local tabl = {}
for i =1, 5 do
table.insert(tabl, i)
-- or simple way to create an indexed array
-- tabl[i] = i
end
print(table.unpack(tabl))

iterating over a table passed as an argument to a function in lua

I am trying using the for _ in pairs() notation to iterate over a table within a function, but if I type anything, even gibberish like print('asdgfafs'), nested inside the for loop, it never gets printed. Code:
record = {bid1,bid2,bid3}
bid1 = {bidTime = 0.05,bidType = 'native'}
bid2 = {bidTime = 0.1,bidType = 'notNative'}
bid3 = {bidTime = 0.3,bidType = 'native'}
function getBids(rec,bidTimeStart,bidTimeFinish,bidType,numberOfBids)
wantedBids = {}
bidCount = 0
for i,v in pairs(rec) do
print('asdfasdfasdfa')
print(i .. ' + ' .. v)
end
end
getBids(record,0,1,'native',5)
Can anyone tell me why and suggest a workaround?
You are creating the record table before creating the bid# tables.
So when you do record = {bid1, bid2, bid3} none of the bid# variables have been created yet and so they are all nil. So that line is effectively record = {nil, nil, nil} which, obviously, doesn't give the record table any values.
Invert those lines to put the record assignment after the bid# variable creation.

How to create the equivalent of a HashMap<Int, Int[]> in Lua

I would like to have a simple data structure in lua resembling a Java HashMap equivalent.
The purpose of this is that I wish to maintain a unique key 'userID' mapped against a set of two values which get constantly updated, for example;
'77777', {254, 24992}
Any suggestions as to how can I achieve this?
-- Individual Aggregations
local dictionary = ?
-- Other Vars
local sumCount = 0
local sumSize = 0
local matches = redis.call(KEYS, query)
for _,key in ipairs(matches) do
local val = redis.call(GET, key)
local count, size = val:match(([^:]+):([^:]+))
topUsers(string.sub(key, 11, 15), sumCount, sumSize)
-- Global Count and Size for the Query
sumCount = sumCount + tonumber(count)
sumSize = sumSize + tonumber(size)
end
local result = string.format(%s:%s, sumCount, sumSize)
return result;
-- Users Total Data Aggregations
function topUsers()
-- Do sums for each user
end
Assuming that dictionary is what you are asking about:
local dictionary = {
['77777'] = {254, 24992},
['88888'] = {253, 24991},
['99999'] = {252, 24990},
}
The tricky part is that the key is a string that can't be converted to a Lua variable name so you must surround each key with []. I can't find a clear description of rule for this in Lua 5.1 reference manual, but the Lua wiki says that if a key "consists of underscores, letters, and numbers, but doesn't start with a number" only then does it not require the [] when defined in the above manner, otherwise the square brackets are required.
Just use a Lua table indexed by userID and with values another Lua table with two entries:
T['77777']={254, 24992}
This is possible implementation of the solution.
local usersTable = {}
function topUsers(key, count, size)
if usersTable[key] then
usersTable[key][1] = usersTable[key][1] + count
usersTable[key][2] = usersTable[key][2] + size
else
usersTable[key] = {count, size}
end
end
function printTable(t)
for key,value in pairs(t) do
print(key, value[1], value[2])
end
end

Does a function in VBscript take variable number of arguments?

For example, if I have a function in VBscript:
Function sum(a, b, c)
sum = a + b + c
End function
Now, in the main, I make two variables and pass them into the function sum as the following:
Dim a : a = 1
Dim b : b = 2
Call sum(a, b)
Will this work or not, and why? Thanks.
It will not work, VBScript doesn't support optional arguments.
I'd use a function that takes an array of numbers instead vary number of arguments to getting sum.
Function sum(nums)
Dim i, out
For i = 0 To UBound(nums)
out = out + nums(i)
Next
sum = out
End function
Call sum(Array(1, 2, 3, 4))
According to this, VBscript does not support optional arguments. You can do what they suggest and pass null values to your function.
I hope this might help.
I use dictionary object to pass variables to function so I can add new arguments without the need for refactoring existing code.
dim params
set params = CreateObject("Scripting.Dictionary")
'...when I want to call a function
params.add "variable_name", value: params.add "variable_name_2", value ': ...
call fn_function_name(params)
'...declaring a function
function fn_function_name(byRef params_in)
'here I usually make sure that variable is of correct type, or that is set
params_in("variable_name") = fn_check(params_in("variable_name"), "number") ' fn_check is a separate function
' ... function code goes here ...
' in order to user external dictionary "params" multiple times, I empty dictionary before exiting the function. This is possible because I set it as a reference (byRef) instead of value
params_in.removeAll()
end function
VBScript doesn't support optional arguments or method overloading. You can pass in null values to your function call, however.

Resources