The interative status of a for loop inside a function - function

Say that we have this function:
def my_function:
for i in some_iterable:
do_something();
When I call this function inside another for loop:
for i in something:
my_function()
Does the for loop in my_function() maintain the status of i or does the loop start from i = 0 each time the function is called? If latter is the case, how can I continue to iterate the for loop inside the function every time the function is called?

The i variable in your main loop and i variable inside my_function (let's call it i') are two different variables. After the end of function execution,
you don't have an access to i', but you have access to i. If you would like to save the "end state" of i', you could consider using generators.
https://realpython.com/introduction-to-python-generators/
Another approach is to pass i' as an argument and return the end state.
def my_function(start_i):
# code using start_i
return end_i

Related

Retrieving A Function From A WebhookScript Global Variable

In WebhookScript, I can store a function in a variable with:
sub = function(a, b) {
return a - b
}
I'd like to store a function in a Global Variable so that I can use it in multiple Custom Actions. But if I've saved the above function as $sub$ then
sub2 = var('$sub$')
subX = sub(1,2)
causes an error:
Trying to invoke a non-function 'string' # line...
And
function subX(a,b){
var('$sub$')
}
when sub only contains return a - b, doesn't work either.
Obviously I need to convert the string to a function but I'm not sure whether that's possible.
I know this is a bit of an obscure language but if anyone knows how this can be done in similar languages like JavaScript and PHP, I'm happy to test out any guesses...
The solution here is to remove the function section and just enter the script, which inherits the execution scope so if my global variable $script$ is:
return 'hello ' + a
Then I can execute the function with:
a = 'world'
value = exec(var('$script$'))
echo(value)
(credit to Webhook.Site's support team for explaining this)

Assigning function to Global Variable in Lua

This is the sample test code.
s="\\command{sample execution}"
u=string.gsub(s,"\\(%b{})",print)
It works fine as print is global function. I defined function myprint as follows.
myprint = function(x,y)
return print(x,y)
end
Now the command u=string.gsub(s,"\\(%b{})",myprint) does not work. This is because the myprint is not global variable as the print is. So basic question that I want to ask is "How to assign function to global variable in Lua?"
You just need to write:
global_function_1 = function (arg)
-- body
end
or use the syntactic sugar alternative:
function global_function_2 (arg)
-- body
end
Make sure that the part in which you do that doesn't have a local variable with selected name. For instance none of the following functions are global:
local bar
local function foo (arg)
local zee
function arg () end
zee = function () end
function bar () end
end
Please note that I have totally ignored assigning to table members and ignored existence of _G and _ENV, and let's leave it this way.
I think that it is worth mentioning that the string.gsub (or really any function call) doesn't care whenever the function (or any argument) is local or whatever:
local str = "abc"
local function fn (x) print(x) end
string.gsub(str, "%a", fn)
outputs:
a
b
c

Need to create a Lua function dynamically

I am trying to create a Lua function "on the fly", from within another function. The new Lua function, to be called "fx", should operate on a scalar variable -- say, x -- and return f_x(x), where f_x(x) could be something such as "x+1" or "x^2". Importantly, the function name "fx" is given (as it will be used, with this name, from within other functions), but its properties -- specifically, whether it returns "x+1" or "x^2" -- should be modifiable dynamically.
Suppose that "x" is the scalar-valued input variable and that "y" is a string that contains an instruction, such as "x+1" or "x^2", that "fx" is supposed to impose on "x". I've naively tried
function make_func (x,y)
return ( function fx(x) return y end )
end
but that doesn't work.
Any help and guidance will be greatly appreciated!
It's not clear how "fx" is supposed to enter the picture, but if you have a string that contains potentially executable Lua code (a Lua expression which would compile if done so in a context where "x" exists), then this seems to be a simple case of building a string from bits of Lua code and executing it:
function make_func (x, lua_op)
return dostring("return function(x) return " .. lua_op .. " end")
end
This requires lua_op to store a string which is a legitimate Lua expression.
If you want to store the function in the global variable "fx", you can do that before returning it:
function make_func (x, lua_op)
fx = dostring("return function(x) return " .. lua_op .. " end")
return fx
end

Lua function needs to be assigned to variable

I have been trying to learn some lua recently, and I came across something I didn't understand with functions today, the code below didn't work
function iter()
local i=0
return function() print(i); i=i+1; end
end
iter()
iter()
I had to assign a variable to my function iter() and then call the variable before it would run:
function iter()
local i=0
return function() print(i); i=i+1; end
end
it=iter()
it()
it()
can anyone clarify why that is?
First of all, functions are just values. Your outer function is assigned to the variable iter. That function returns an anonymous function. ("Anonymous" just means you did not give the function a name before returning it.)
Secondly, an argument list in parentheses is basically an operator that calls a function (unless it's in a function declaration). When you use that operator, the function runs and the expression results in the return value.
In the statement iter(), you call a function and ignore its return value, so you never get to see the inner function run.
In the statement it = iter(), you end up with a named function called it. Every time you call it, it increments the i variable from inside the iter call that created it.
As a side note, it would be legal to say iter()() to immediately call the returned function. This wouldn't actually be useful in your case, because each call to iter returns a fresh closure with i starting at zero.

Lua: How to Properly Construct Nested Functions

I'm trying to create a function with local functions within it. The main function would receive an output from an outside source, and the functions within it would be required to translate that input and return results for later use. My problem is that the way I am currently attempting this, when I try to put in my first local function inside the main function, I continue to get nil. Here is an example:
function stats(input)
height, weight, name, age, gender, relate = string.match(input, "(%d*)ft,(%d*)lbs,(%w*),(%d*),(%u*),(%u)")
if name then
function nameInit(relate)
relateTable = {["F"] = "Friend", ["R"] = "Relative"}
for k,v in pairs (relateTable) do
if relate == k then
relship = v
return relship
end
end
end
end
person = name.." is "..age.." years old, weighs "..weight.." and blah blah blah....
return person
end
print (stats("5.8ft, 160lbs, Mike Scott, 19, M, F"))
Obviously, this subject isn't practical but what I'm trying to do is along the same lines in terms of end response. I'm currently getting lua: filename: attempt to concatenate global 'relship' (a nil value)? I can get the response I want without the nested function. But when I try to elaborate more on the response I would like to receive, and place that function inside the global function, I begin to get these response(s). This seems to be my problem anytime I attempt to use functions within other functions. I can make two separate global functions and print results from either one. But the minute I try to use one within another, I screw myself up. Anyone who can take some time to help a beginner better understand what he is doing wrong would be great! Thanks all.
Based on your statement "the functions within it would be required to translate that input and return results for later use", I'm not sure that nested functions is what you want. You say that when you have two global functions your code works:
function func1(args)
...
end
function func2(args)
...
end
but when you nest (for example) func1 inside func2, it no longer works. Lua does allow you to define nested functions, but I can only think of two reasons to use them:
to return a function that encapsulates a task, usually with some of the wrapper function's args and/or locals as upvalues.
to encapsulate some logic in a function to be called from within the wrapper function, with no need for any other functions to call it.
For example of case 1:
function func2(a, b, c)
function func1()
do something with a, b, c eventhough they are not args of func1
return result
end
return func1
end
someFunc = func2(1,2,3)
....
result = someFunc() -- calls func1 created inside func2, using 1,2,3
For example of case 2:
function func2(a, b, c)
function func1()
do something with a, b, c eventhough they are not args of func1
return result
end
result = func1()
...
end
func2(1,2,3)
You could also add a nested function to a table object (class) passed as argument, but I see this as a variation on case 1.