How to create a function return nothing in Julia? - function

When I create a function in Julia, I print something in the function and don't return anything. But the result is the function print what I want and also return 'nothing'. What can I do to make the function just print what I want without return 'nothing'?

There is always a return value from a function. When there is no explicit return statement, the value of the last expression in the function is returned. This is probably what you're seeing here: if the print statement is the last line of your function, since print's return value is nothing, that becomes the return value of your function too.
If you just don't want the nothing shown at the end of the output,then please paste the code you're using that leads to this behaviour, and we can figure out how to suppress this output of nothing from appearing.

Some additional comment to the answer by #sundar.
In other words nothing is the value meaning that the function did not return anything. Consider this Julia session:
julia> function f()
end
f (generic function with 1 method)
julia> res = f()
julia> dump(res)
Nothing nothing
By default nothing is displayed as an empty output:
julia> res
This however changes when res ends up interpolated in another string:
julia> "$res"
"nothing"
For cases like above consider using something such as:
julia> "$(something(res,""))"
""

Related

In Julia, why can "if false" statements in local scope modify function definitions?

In Julia 1.4.1, if I define a function in a global scope, modifications after "if false" statements do not affect it, as expected:
test()=0
if false
test()=1
end
println(test())
This prints "0", as it should. However, when I enclose this code within a local scope, the behavior changes:
function main()
test()=0
if false
test()=1
end
println(test())
end
main()
This now prints "1" which I did not expect. If I change "test" to be an array or a float I observe no modification as expected, i.e. the problem does not occur. Why does Julia behave this way for functions?
The solution is to use anonymous functions in cases like this:
function main()
test = () -> 0
if false
test = () -> 1
end
println(test())
end
julia> main()
0
As for the why, this gets to the core of what it means to define and redefine a particular method of a function.

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.

How to implement a basic Lua function in Conky?

I am trying to add a function to my Conky which prints the length of a string for debug purposes. The code, inside a file called test.lua, is pretty trivial:
function test(word)
return string.len(word)
end
...and I load it like this. In my conky.config section I have:
lua_load = '/home/xvlaze/test.lua',
lua_draw_hook_pre = 'test'
...in the conky.text section I have:
${lua test "fooo"}
...where test is the name of the function and fooo the string to test.
The expected result should be a printed 4 in Conky, but instead of that I get:
conky: llua_do_call: function conky_test execution failed: /home/xvlaze/test.lua:2: attempt to index a nil value (local 'string')
conky: llua_getstring: function conky_test didn't return a string, result discarded
I have browsed through the documentation, but I can't find anything. Does anybody know where the failure is?
Several guidances on how to implement functions in Conky:
First of all: YOU MUST USE conky_ BEFORE YOUR FUNCTION'S NAME.
Otherwise, you will get the following error when running your Conky:
attempt to call a nil value
Secondly: YOU MUST ALWAYS RETURN A VALUE.
I don't mind repeating it - it is crucial. Otherwise, you will get:
function foobar didn't return a string, result discarded
function_result
...in your terminal, and your Conky will be left empty of values related to your extra code. Nothing will be printed regarding your function.
Last but not least: YOU MUST ALWAYS CALL YOUR FUNCTION LIKE:
lua_load = '/path/to/function.lua',
-- Whatever content...
${lua function_name function_parameter1 function_parameterN} -- In case you use more than one parameter.
In summary, a dummy function template could be:
MAIN FILE (conky.conf):
conky.config = {
-- Whatever content... Lua styled comments.
lua_load = '/path/to/function.lua',
}
conky.text = [[
# Whatever content... In this section comments are started with '#'!
${lua function_name parameter}
]]
FUNCTION FILE:
function conky_function_name(parameter)
-- Whatever content... Remember this is Lua, not conky.text syntax. Always use '--' comments!
return whatever -- No return, no party. A function MUST always return something!
end

How to call a function with less arguments that is set (Python 3)

I am making a terminal emulator in Python 3. The commands are being stored in functions, like:
def rd(os_vartmp, os_vartmp2):
if os_vartmp == None:
print('rd [path] [-S]')
print('Delete a folder')
else:
if os.path.isfile(os_vartmp) == True:
if os_vartmp2 == '-S': print('a')
else:
print(ERR5)
a = input('Command: ')
The terminal works like this:
Asks user for input
Splits the input
Uses the first part of input to search a function in locals
If there is one, uses the rest part of input as argument
Calls the function
The thing here is, when i call the function 'rd' with, for example, 'rd "boot.py" -S' it works just fine. But if i need to call it like this: rd "boot.py", it throws me a error about 1 argument given when 2 are required. Is there a fix for that?
You can make an argument optional by assigning a value in the method definition. For example:
def Add(x=0, y=0):
return x+y
If you input only one value, y will default to 0. If I wanted to give y a value but have x fall back on it's default value I could do Add(y=10). I hope this helped!
Have you tried this?
def rd(os_vartmp, os_vartmp2="-S"):
Instead of trying to get null value, which would require rd("boot.py",null), you can ser default value and then you can do rd("boot.py").
Hope it works.

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.