Question in the code comments:
function find($id, Application_Model $guestbook)
{
$result = $this->getDbTable()->find($id);
if (0 == count($result)) {
return; // what is returned in functions like these?
}
The PHP documentation says "If no parameter is supplied ... NULL will be returned." So this:
return;
is equivalent to:
return null;
It doesn't return anything. That said, if you try to assign the output of that function to a variable, then that variable will be null.
function iDoNothing()
{
return;
}
$returnValue = iDoNothing();
// $returnValue is now null
Return statements with no argument return null.
You can try this yourself by creating a short php script:
<?php
echo emptyReturn();
function emptyReturn() {
return;
}
?>
It's actually dependent on the language. Here's a list for a few of them ("if value omitted, return" column): http://en.wikipedia.org/wiki/Return_statement
In the case of PHP, it simply returns NULL.
In a language like C/C++, the behavior is undefined. Meaning it could return junk information.
This is why languages like Java prevent you from doing this. Java will give you a compiler error if you try to return; within a non-void function.
Edit: Actually that Wikipedia page didn't really have much info on this, so I added some to it.
Related
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)
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
This is my first cut:
const planLimits = {plan1: {condition1: 50, ...}}
function initialisePlanLimits(planLimits) {
const limits = new Map();
Object.keys(planLimits).map((planId) => (
const limitMap = new Map(Object.entries(planLimits[planId]));
limits.set(planId, limitMap);
));
return limits;
}
The linter flags this error: error Expected to return a value in this function array-callback-return
So I changed to this version:
function initialisePlanLimits(planLimits) {
const limits = new Map();
Object.keys(planLimits).map((planId) => (
limits.set(planId, new Map(Object.entries(planLimits[planId])))
));
return limits;
}
It throws another error Unexpected parentheses around single function argument having a body with no curly braces arrow-parens
My questions:
1) I reckon I can fix my first version by sticking in a return null within the curry bracket. But is there a better, more elegant way? A bogus return statement does not make sense in this context
2) Why the second version fails? Isn't it equivalent to the first version?
If I use forEach instead of map, it will not cause the array-callback-return lint error
Object.keys(planLimits).forEach((planId) => (
const limitMap = new Map(Object.entries(planLimits[planId]));
limits.set(planId, limitMap);
));
Well, accepted answer advocates about using 'forEach,' which is true. Please read below explaination from ESLint documentation,
Array has several methods for filtering, mapping, and folding. If we forget to write return statement in a callback of those, it's probably a mistake. If you don't want to use a return or don't need the returned results, consider using .forEach instead.
TLDR: ESLint and Function Return Values
This issue is caused by not returning a value when using map(), see how the results are expected according to the docs...
The map() method creates a new array populated with the results of calling a provided function on every element in the calling array. (Source: MDN WebDocs.)
Demonstration of Issue in JavaScript
With this code sample of JS, which shows a group of elements...
var newarray = [];
array.map( (item, index) => {
newarray.push('<li>' + item + '</li>');
});
I get this error...
Expected to return a value in arrow function array-callback-return
The error goes away if I add a single return to the above function, like so :
var newarray = array.map( (item, index) => {
return '<li>' + item + '</li>';
});
`map()` - So why should I use it?
You can clearly see elsewhere, too, on MDN Docs, that what is returned is, "A new array with each element being the result of the [return value of the] callback function." So, if you are using map(), it's also a very good idea to also use return returnvalue!
map() is a powerful tool. Don't throw that tool away.
I seem to remember there being a special name for a function whose output is always identical to its input, e.g.:
var whatsMyName = function (a) {
return a;
};
Does anyone know what such a function -- which, in practice, is pretty pointless -- is called?
It's the identity function.
I'm trying to do something like the following
<div id="test">
#(
string.IsNullOrEmpty(myString)
? #:
: myString
)
</div>
The above syntax is invalid, I've tried a bunch of different things but can't get it working.
Try the following:
#Html.Raw(string.IsNullOrEmpty(myString) ? " " : Html.Encode(myString))
But I would recommend you writing a helper that does this job so that you don't have to turn your views into spaghetti:
public static class HtmlExtensions
{
public static IHtmlString ValueOrSpace(this HtmlHelper html, string value)
{
if (string.IsNullOrEmpty(value))
{
return new HtmlString(" ");
}
return new HtmlString(html.Encode(value));
}
}
and then in your view simply:
#Html.ValueOrSpace(myString)
You could do:
#{
Func<dynamic, object> a = (true ?
(Func<dynamic, object>)(#<text> Works1 </text>)
: (Func<dynamic, object>)(#<text> Works2 </text>));
#a(new object());
}
Or to make it inline do:
#(
((Func<dynamic, object>)(true == false
? (Func<dynamic, object>)(#<text> Works2 </text>)
: (Func<dynamic, object>)(#<text> Works3 </text>)))
(new object())
)
(Note that all of the above will work one line as well, I have just separated them for clarity)
However the original intention of the OP can alos be modified to work, but this time line breaks must be preserved:
#(((Func<dynamic, object>)( true == true ? (Func<dynamic,object>)(#: Works
): (Func<dynamic, object>)(#: Not Works
)))("").ToString())
Note
In fact you need the cast only on one of the options in the operator, and also you don't have to give dynamic as the first option to Func, you can give just anything, and the same when evaluating you can give anything as long it matches the first argument to Func.
For example you can do the following (which I think is the shortest version):
#(
((Func<int, object>)(true == false
? (Func<int, object>)(#<text> Works2 </text>)
: #<text></text>))
(0)
)
If you use it a lot, it would be a good idea to inherit Func as in
public class Razor : Func<dynamic, object>{}
Or one can even write a wrapper method (or even a lambda expression in which case [I am not sure but it might be possible] to use a regular ternary operator and defer the cast to the callee) for the ternary operator.
Another updated approach thanks to new features is to create a helper function right in the view. This has the advantage of making the syntax a little cleaner especially if you are going to be calling it more than once. This is also safe from cross site scripting attacks without the need to call #Html.Encode() since it doesn't rely on #Html.Raw().
Just put the following right into your view at the very top:
#helper NbspIfEmpty(string value) {
if (string.IsNullOrEmpty(value)) {
#:
} else {
#value
}
}
Then you can use the function like this:
<div id="test">
#NbspIfEmpty(myString)
</div>
#(string.IsNullOrEmpty(myString)? ": ": myString)