Weird return statement in Lua
The return
statement expects an expression as its argument. That means that if you write return expression
, the evaluated value of expression
is to be returned.
In this specific case, Memory.value("game", "textbox") == 1
is an expression that evaluates to true
if the return value of Memory.value("game", "textbox")
equals 1
. If Memory.value("game", "textbox")
was to be a value different than 1
, the expression would evaluate to false
, which is what the return
statement would return.
You could easily write the given statement as
if (Memory.value("game", "textbox") == 1) then
return true
else
return false
end
But as this is logically redundant, you would want to avoid writing this code and instead use the one liner you provided.
return
is a keyword, and does not have a condition as an argument, rather an expression. If you explicitly state return
it WILL return. It evaluates it's arguments however, which is when the logical aspect comes into play.
I'm going to get into the logical aspect.
==
is a comparison operator, it checks if it's arguments are equal to eachother. If so it returns true. So when used in a return
, return
will evaluate and return true if they are equal.
This is not limited to ==
, any comparison operators (~=
, <=
, >=
, <
, >
) will do the exact same thing.
and
, or
works a little differently however. They don't return true/false. Here's how they behave:
return a and b
: This basically evaluates to if a is true (neither false nor nil) return b
return a or b
: This basically translates to *if a is true (neither false nor nil) return a, otherwise return b
So as you could imagine, something like return a and b or c
means
if a then
if b then
return b
else
return c
end
else
return c
end
So return a and b or c
is the equivalent to return ((a and b) or c)
And for the sake of completion, not
simply evaluates it and inverts it, so if it's false/nil it returns true, otherwise returns false.
Your question says that you know Perl. No, it's not like Perl, where the condition of `if' and similar statements can follow the statement.
return
expects a list of zero or more return values. A function can return any length list. It can also have any number of return statements, and they need not return lists of the same length or meaning. So, the function's documentation is essential. See load as an example.
This statement returns true
or false
.
It treats the value referenced by Memory as a table, indexes it with "value", calls the resulting value as a function with two string arguments and compares the result of the function call with the value 1.