Lua function needs to be assigned to variable - function

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.

Related

The interative status of a for loop inside a 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

How to call a function within a function in Lua?

I have this code:
function test()
function awesome()
print("im awesome!")
end
function notawesome()
print("im not awesome.")
end
function notevenawesome()
print("im not even awesome...")
end
end
test().notawesome()
When I run this, the console prints
15: attempt to index a nil value
What I'm trying to do is call the function notawesome() within the function test(), how would I do that?
Your function is not returning anything (thus returning nil). Something like this should work:
function test()
function awesome()
print("im awesome!")
end
function notawesome()
print("im not awesome.")
end
function notevenawesome()
print("im not even awesome...")
end
result = {}
result["notawesome"] = notawesome
result["awesome"] = awesome
result["notevenawesome"] = notevenawesome
return result
end
test().notawesome()
#Axnyff explains what you might be trying to do. I'll explain what you did.
If you are familiar with other languages, please note that Lua does not have function declarations; It has function definitions, which are expressions that produce a function value when evaluated. Function definition statements, which you have used, are just shortcuts that implicitly include an assignment. See the manual.
When you run your code, a function definition is evaluated and the resulting function value is assigned to the variable test. Then the variable test is evaluated and its value is called as a function (and it is one).
When that function executes, three function definitions are evaluated and assigned to the variables awesome, notawesome, and notevenawesome, repsectively. It doesn't return anything.
So, when the result of calling test (nil) is indexed by the string "awesome", you get the error.
If you wanted to call the function value referred by the variable awesome, just do awesome().
If you want to achieve that instead to use the main function you can use an object:
test = {
awesome = (function()
return 'im awesome!'
end),
notawesome = (function()
return 'im not awesome.'
end),
notevenawesome = (function()
return 'im not even awesome...'
end)
}
To call your functions use this:
print(test.notawesome()) --> im not awesome.

What Meaning Of This Function

function [TC]=Translate(T0,Base)
end
I know that Translate is a function and T0 and Base his parameter but what is [TC]?
Octave (and matlab) have a rather unique way of returning variables from functions. Instead of defining explicitly what to return from the function using a return keyword, they define from the outset which variables will be returned when the function exits, and octave simply looks for those variables by name at the time the function exits, and returns their values, whatever they may be by that point.
Your function may return nothing:
function returnsNothing();
disp('hello, I return nothing');
end
or it may return one output:
function Out = returnsOne(x)
Out = x+5
disp('This function will return the value of Out');
end
or it may return more than one outputs:
function [Out1, Out2] = returnsTwo(x)
Out1 = x+5;
Out2 = x+10;
end
You would call the last function from the octave terminal (or script) like this:
[a,b] = returnsTwo(5); % this will make a = 10 and b = 15

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.

Pascal. Specify to use a variable instead of function with the same name>

I'm writing long digit arythmetics. This is a function for adding to longint long binary digits. I need to output the sum inside the function, to debug it. How could I do it, without creating new variables?
function add(var s1,s2:bindata;shift:longint):bindata;
var l,i:longint;
o:boolean;
begin
writeln(s1.len,' - ',s2.len);
o:=false;
l:=max(s1.len,s2.len);
add.len:=0;
for i:=1 to l do begin
if o then Begin
if s1.data[i+shift] then Begin
if (s2.data[i]) then add.data[i+shift]:=true
Else add.data[i+shift]:=false;
End
else if s2.data[i] then add.data[i+shift]:=false
else Begin
add.data[i+shift]:=true;
o:=false;
End;
End
Else Begin
if s1.data[i+shift] then Begin
if s2.data[i] then
Begin
add.data[i+shift]:=false;
o:=true;
End
Else add.data[i+shift]:=true;
End
else if s2.data[i] then add.data[i+shift]:=true
else add.data[i+shift]:=false;
End;
output(add); //Can I output a variable?
end;
add.len:=l;
if o then Begin
inc(add.len);
add.data[add.len]:=true;
End;
end;
You are accumulating the result of the function within the function result variable, which is generally fine, but uses an outdated style, and leads to exactly the problem you're facing here. You're trying to report an intermediate value of the function result, and to do that, you're trying to reference the name of the function, add. When you do that, though, the compiler interprets it as an attempt to report the function itself, rather than the expected return value of this particular invocation of the function. You'll get the address of the function, if output is defined to accept function addresses; otherwise, you'll get a compiler error.
If your compiler offers a certain common language extension, then you should use the implicit Result variable to refer to the intermediate return value instead of continuing to refer to it by the function name. Since Result is declared implicitly, you wouldn't have to create any other variables. The compiler automatically recognizes Result and uses it as an alias for the function's return value. Simply find every place you write add within the function and replace it with Result. For example:
if o then begin
Inc(Result.len);
Result.data[Result.len] := True;
end;
Turbo Pascal, Free Pascal, GNU Pascal, and Delphi all support the implicit Result variable, but if you've managed to get stuck with a compiler that doesn't offer that extension, then you have no choice but to declare another variable. You could name it Result, and then implement your function with one additional line at the end, like so:
function add(var s1, s2: bindata; shift: longint): bindata;
var
l, i: longint;
o: boolean;
Result: bindata;
begin
{
Previous function body goes here, but with
`add` replaced by `Result`
}
{ Finally, append this line to copy Result into the
function's return value immediately before returning. }
add := Result;
end;