Getting variable from a function - function

function isEven(x)
print("Checking if "..x.." is even.\nWill return state as 1 if true.")
if math.fmod(x, 2) == 0 then
state = 1
end
return state
end
I know that I can just run isEven and then use the state variable. But is there a way to do it in one line?
Like isEven(8).state?
Any and all help is appreciated.

As Egor said in a comment, this is precisely what return values are meant to do. When you see a function call in your code, such as isEven(8), it evaluates into that function's return value.
function isEven(x)
print("Checking if "..x.." is even")
return (math.fmod(x, 2) == 0)
end
print( isEven(8) )
print( isEven(7) )
if isEven(8) then
print("a")
else
print("b")
end
Finally, I would just like to point out a couple of things about the isEven function: First of all if you want you could use the % operator instead of math.fmod. Secondly, in the example I used the function returns a boolean value (true or false) instead of a number (0 or 1).

Related

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

Function does not deliver the desired values in python

I am trying to use both functions below:
def func1():
print('blahblah')
func2()
def func2():
check = 0
while check < 1:
first = input('Integer or pass ')
if first == 'pass':
first = 0
func1()
break
else:
first = int(first)
second = input('Integer or pass')
if second == 'pass':
second = 0
func1()
break
else:
second = int(second)
third = input('Integer or pass' )
if third == 'pass':
third = 0
func1()
break
else:
third = int(third)
check = 1
return first, second, third
The func2 returns None instead of the inputs when once "pass" was entered. What am I doing wrong?
edit: the results should be 3 integers, no matter how many times 'pass' was entered.
After changing the indentation I get following error: UnboundLocalError: local variable 'second' referenced before assignment (in case I start with pass)
For clarifcation: func2 asks for input, if input is "pass" then func1 is called.
After the print func1 calls func2 again . This repeats until 3 integers are input. Their valus shall be returned in th end.
Your indentation is wrong. You need to move the last statement return first, second, third one tab before.

Composing two functions in lua

I just started learning lua, so what I'm asking might be impossible.
Now, I have a method that accepts a function:
function adjust_focused_window(fn)
local win = window.focusedwindow()
local winframe = win:frame()
local screenrect = win:screen():frame()
local f, s = fn(winframe, screenrect)
win:setframe(f)
end
I have several functions that accept these frames and rectangles (showing just one):
function full_height(winframe, screenrect)
print ("called full_height for " .. tostring(winframe))
local f = {
x = winframe.x,
y = screenrect.y,
w = winframe.w,
h = screenrect.h,
}
return f, screenrect
end
Then, I can do the following:
hotkey.bind(scmdalt, '-', function() adjust_focused_window(full_width) end)
Now, how could I compose several functions to adjust_focused_window, without changing it's definition. Something like:
hotkey.bind(scmdalt, '=', function() adjust_focused_window(compose(full_width, full_height)) end)
where compose2 would return a function that accepts the same parameters as full_width and full_height, and internally does something like:
full_height(full_width(...))
As mentioned in the comments, to chain two functions together you can just do:
function compose(f1, f2)
return function(...) return f1(f2(...)) end
end
But what if you want to connect more than 2 functions together? You might ask, is it possible to 'compose' an arbitrary number of functions together?
The answer is a definite yes -- below I show 3 different approaches for implementing this plus a quick summary of their consequences.
Iterative Table approach
The idea here is to call each function in the list one after the other in turn. While doing so, you save the returned results from the previous call into a table and you unpack that table and pass it into the next call.
function compose1(...)
local fnchain = check_functions {...}
return function(...)
local args = {...}
for _, fn in ipairs(fnchain) do
args = {fn(unpack(args))}
end
return unpack(args)
end
end
The check_functions helper above just checks that the stuff passed in are indeed functions -- raises an error if not. Implementation omitted for brevity.
+: Reasonably straight-forward approach. Probably what you'd come up with on a first attempt.
-: Not very efficient on resources. A lot of garbage tables to store results between calls. You also have to deal with packing and unpacking the results.
Y-Combinator Pattern
The key insight here is that even though the functions we're calling isn't recursive, it can be made recursive by piggy-backing it on a recursive function.
function compose2(...)
local fnchain = check_functions {...}
local function recurse(i, ...)
if i == #fnchain then return fnchain[i](...) end
return recurse(i + 1, fnchain[i](...))
end
return function(...) return recurse(1, ...) end
end
+: Doesn't create extra temporary tables like above. Carefully written to be tail-recursive -- that means no extra stack space needed for calls to long function chains. There's a certain elegance to it.
Meta-script generation
With this last approach, you use a lua function that actually generates the exact lua code that performs the function call chain desired.
function compose3(...)
local luacode =
[[
return function(%s)
return function(...)
return %s
end
end
]]
local paramtable = {}
local fcount = select('#', ...)
for i = 1, fcount do
table.insert(paramtable, "P" .. i)
end
local paramcode = table.concat(paramtable, ",")
local callcode = table.concat(paramtable, "(") ..
"(...)" .. string.rep(')', fcount - 1)
luacode = luacode:format(paramcode, callcode)
return loadstring(luacode)()(...)
end
The loadstring(luacode)()(...) probably needs some explaining. Here I chose to encode the function chain as parameter names (P1, P2, P3 etc.) in the generated script. The extra () parenthesis is there to 'unwrap' the nested functions so the inner most function is what's returned. The P1, P2, P3 ... Pn parameters become captured upvalues for each of the functions in the chain eg.
function(...)
return P1(P2(P3(...)))
end
Note, you could also have done this using setfenv but I chose this route just to avoid the breaking change between lua 5.1 and 5.2 on how function environments are set.
+: Avoids extra intermediate tables like approach #2. Doesn't abuse the stack.
-: Needs an extra byte-code compile step.
You can iterate through the passed functions, successively invoking the next function in the chain with the results from the previous.
function module._compose(...)
local n = select('#', ...)
local args = { n = n, ... }
local currFn = nil
for _, nextFn in ipairs(args) do
if type(nextFn) == 'function' then
if currFn == nil then
currFn = nextFn
else
currFn = (function(prev, next)
return function(...)
return next(prev(...))
end
end)(currFn, nextFn)
end
end
end
return currFn
end
Note the use of Immediately Invoked Function Expressions above, which allow the re-used function variables to not invoke an infinite recursive loop, which happens in the following code:
function module._compose(...)
local n = select('#', ...)
local args = { n = n, ... }
local currFn = nil
for _, nextFn in ipairs(args) do
if type(nextFn) == 'function' then
if currFn == nil then
currFn = nextFn
else
currFn = function(...)
return nextFn(currFn(...)) -- this will loop forever, due to closure
end
end
end
end
return currFn
end
Although Lua doesn't support ternary operators, short-circuit evaluation can be used to remove the inner if statement:
function module.compose(...)
local n = select('#', ...)
local args = { n = n, ... }
local currFn = nil
for _, nextFn in ipairs(args) do
if type(nextFn) == 'function' then
currFn = currFn and (function(prev, next)
return function(...)
return next(prev(...))
end
end)(currFn, nextFn) or nextFn
end
end
return currFn
end

Lua - convert a table into a comma separated list

I need to convert a table into a comma separated list in order to save it to a text file. Is there a built in method for doing this in Lua?
If your table is an array, you can use table.concat to print CSVs:
t={10,20,30}
print(table.concat(t,","))
outputs 10,20,30.
There isn't a built in function, but there are examples onthe web.
This is a decent one actually.
No, there is not a "built in" function for this. But it's not hard to do it yourself. I keep a script around for recursively writing Lua tables directly to files as Lua scripts, which can then be loaded and executed like Lua scripts.
--This file exports a function, WriteTable, that writes a given table out to a given file handle.
local writeKey = {};
function writeKey.string(hFile, value, iRecursion)
WriteFormatted(hFile, "[\"%s\"]", value);
end
function writeKey.number(hFile, value, iRecursion)
WriteFormatted(hFile, "[%i]", value);
end
local writeValue = {};
function writeValue.string(hFile, value, iRecursion)
WriteFormatted(hFile, "[==[%s]==]", value);
end
function writeValue.number(hFile, value, iRecursion)
WriteFormatted(hFile, "%i", value);
end
function writeValue.boolean(hFile, value, iRecursion)
if(value) then hFile:write("true"); else hFile:write("false"); end;
end
function writeValue.table(hFile, value, iRecursion)
WriteTable(hFile, value, iRecursion)
end
local function WriteFormatted(hFile, strFormat, ...)
hFile:write(string.format(strFormat, ...));
end
local function WriteForm(hFile, strFormat, ...)
hFile:write(string.format(strFormat, ...));
end
local function WriteTabs(hFile, iRecursion)
for iCount = 1, iRecursion, 1 do
hFile:write("\t");
end
end
function WriteTable(hFile, outTable, iRecursion)
if(iRecursion == nil) then iRecursion = 1; end
hFile:write("{\n");
local bHasArray = false;
local arraySize = 0;
if(#outTable > 0) then bHasArray = true; arraySize = #outTable; end;
for key, value in pairs(outTable) do
if(writeKey[type(key)] == nil) then print("Malformed table key."); return; end
if(writeValue[type(value)] == nil) then
print( string.format("Bad value in table: key: '%s' value type '%s'.", key, type(value)));
return;
end
--If the key is not an array index, process it.
if((not bHasArray) or
(type(key) ~= "number") or
not((1 <= key) and (key <= arraySize))) then
WriteTabs(hFile, iRecursion);
writeKey[type(key)](hFile, key, iRecursion + 1);
hFile:write(" = ");
writeValue[type(value)](hFile, value, iRecursion + 1);
hFile:write(",\n");
end
end
if(bHasArray) then
for i, value in ipairs(outTable) do
WriteTabs(hFile, iRecursion);
writeValue[type(value)](hFile, value, iRecursion + 1);
hFile:write(",\n");
end
end
WriteTabs(hFile, iRecursion - 1);
hFile:write("}");
end
There is not a built in way, but there are a number of options that are relatively easy if you want to build it yourself. Here are some links that can help you figure out how you want to put it together:
http://www.lua.org/pil/12.1.html
http://lua-users.org/wiki/TableSerialization
Yes, there is a builtin method, and its been around for a very long time.
-- table.concat
local line = { "Fred", 20, 4.000 }
print(table.concat(line,","))
Output: Fred, 20, 4.000
You can convert a table to a string using this function, and simply choose a "," for a separator.
You can also add a function that runs during concatenation and detects how many properties you have written, then add a new line - you can make a very complex converter if you need.
My recommendation is to break each "line" of comma separated tables and concat each one with "," then write it out. This way you can be sure that you can handle large numbers of lines, and that each line is correctly formatted.
Caveats:
You will have to handle strings with commas, quotes and so forth.
This method is mainly for ordered tables (lists or arrays). They must be indexed.
If you need to do processing on your values in the table, do it first. Then concat.
Reference for concat:
http://www.lua.org/manual/5.1/manual.html#pdf-table.concat

Lua return from function problem

I'm trying to parse some xml files with lua and
I'm stuck on this function:
function get_node_by_id (xml, nodeId)
for i=1, #xml, 1 do
if get_attr_by_name(xml[i], 'Id') == nodeId then
print ("TRUEEEEE", i, xml[i])
return xml[i]
else
get_node_by_id(xml[i], nodeId)
end
end
end
The problem is that print("TRUEEEEE", i, xml[i]) works, but it returns nil in the next line return xml[i].
What am I doing wrong?
You are calling the function recursively, but only provide a single return. If you happen to find the node you are looking for in second level, you only return the value to first level, which doesn't do anything with it.
Maybe you want something like this (untested code):
function get_node_by_id (xml, nodeId)
for i=1, #xml, 1 do
if get_attr_by_name(xml[i], 'Id') == nodeId then
print ("TRUEEEEE", i, xml[i])
return xml[i]
else
local node = get_node_by_id(xml[i], nodeId)
if node then return node end
end
end
end
I think you're missing a return in the else block:
return get_node_by_id(xml[i], nodeId)