evaluating variable and assigning to another variable in one line - lua

I have a variable that's returned from the db as a string. I convert it to a number and then test like so:
if tonumber(v.active) == 1 then
elements.active.value = true
else
elements.active.value = false
end
The value in elements.active.value is being used to diplay a checkbox. I'm wondering if there's a way to combine this all into one statement?
EDIT 1
I'm using a lua boolean value to set the checkbox, so I can't use 1. You have to use true / false.
I'm not so much interested in whether or not I can use 1 or true to set the value. I'm more interested in keeping the logic the same, but simplifying.
What I was really after was something like what you can do in php like so:
max = array_key_exists ('max', $options) ? $options['max'] : 0;
it'll use either the $options['max'] value or 0 depending on the eval.

Like this:
elements.active.value = tonumber(v.active) == 1
Because the result of a relational operator like == is boolean, just what you assigned to elements.active.value in your piece of code.
Lua reference manual: Relational Operators
The relational operators in Lua are
== ~= < > <= >=
These operators always result in false or true.

Related

nil check, best way?

I'm just learning lua, and see these two ways to check for nil
local stats = game.ServerStorage.PlayerMoney:FindFirstChild(player.Name)
if (stats ~= nil) then
-- do stuff
end
if (stats) then
-- do stuff
end
Are the if statements equivalent? If so, is there any advantage to including the extra "~= nil" part?
Statement "~= nil" works also if stats = false.
You can read in docs:
The condition expression of a control structure can return any value.
Both false and nil are considered false. All values different from nil
and false are considered true (in particular, the number 0 and the
empty string are also true).

Comparing Julia variable to `nothing` using !== or !=

In some Julia code when can see conditional expression such as
if val !== nothing
dosomething()
end
where val is a variable of type Union{Int,Nothing}
What is the difference between conditons val !== nothing and val != nothing?
First of all, it is generally advisable to use isnothing to compare if something is nothing. This particular function is efficient, as it is soley based on types (#edit isnothing(nothing)):
isnothing(::Any) = false
isnothing(::Nothing) = true
(Note that nothing is the only instance of the type Nothing.)
In regards to your question, the difference between === and == (and equally !== and !=) is that the former checks whether two things are identical whereas the latter checks for equality. To illustrate this difference, consider the following example:
julia> 1 == 1.0 # equal
true
julia> 1 === 1.0 # but not identical
false
Note that the former one is an integer whereas the latter one is a floating point number.
What does it mean for two things to be identical? We can consult the documentation of the comparison operators (?===):
help?> ===
search: === == !==
===(x,y) -> Bool
≡(x,y) -> Bool
Determine whether x and y are identical, in the sense that no program could distinguish them. First the types
of x and y are compared. If those are identical, mutable objects are compared by address in memory and
immutable objects (such as numbers) are compared by contents at the bit level. This function is sometimes
called "egal". It always returns a Bool value.
Sometimes, comparing with === is faster than comparing with == because the latter might involve a type conversion.

What is local name = value or 0 in lua?

What does this block of code do?
local name = value or 0
Please tell me that it makes it zero if nil and makes it value if not nil.
Short answer
yes
Looooong answer
You're right. While in other languages, the logical operators return either true or false, Lua (and some other languages) does something more clever:
When the first parameter of or is truthy, it evaluates to that value, if it's not, it evaluates to the second one. And does it the other way around: if its left-hand-side is falsey, it evaluates to that, otherwise it evaluates to its RHS.
Logically, this means that or evaluates to truthy if either operand is truthy and and evaluates to falsey if either of its operands is.
This is often used as an equivalent of
if value then
name = value
else
name = 0
end
And it effectively does the same. It is also often use to assign default values to variables like this:
function call(name)
name = name or "you"
print("Hey "..name.."! Come here for a moment!")
end
Note though, that this doesn't work
function alarm(real)
real = real or true
print "ALAAARM!"
if real then print "This is NOT a drill!" end
end
alarm(false)
This will always print "ALAAARM!" "This is NOT a drill!", because false is evaluated as falsey, so the or statement evaluates to its RHS, which is true. In this particular example, you would have to check explicitly if the argument is nil.
-- ...
real = (real == nil) and true or real
-- ...
This would work as intended, because only if real == nil, the and statement evaluates to true, and the or thus evaluates to its LHS. If real == nil is false, then the and evaluates to that, thus the or statement evaluates to its RHS (because its LHS is false).
It's also worth mentioning that both and and or are short-circuited. What this means is:
function foo(bar)
print(bar)
return bar
end
io.write "First: "
local A = foo(nil) or foo(false)
io.write "Second: "
local B = foo(true) or foo(true)
This will print "First: nil false" on the first two lines, but then "Second: true" on the third line. The last call to foo is not even executed, because at that point the or statement already knows it's going to return its left operand.

Test variable for Numeric in one line

I found this code on another thread.
def is_number? string
true if Float(string) rescue false
end
Instead of using a method to return true or false, I'd like to do this "is_numeric" test in one line, in an if statement. Can someone explain if this is possible? I'm getting errors at the moment both when the string variable is null and when it contains non-numeric characters.
if Float(string)
* do something
else
* do something else
end
if Float() is pointless code, since Float() will either return a truthy value or raise an error (based on my limited look at the source code - as of writing, you can follow the code path from line #2942). I'd suggest you're asking the wrong question/looking at the problem wrong (it'd be helpful to know what you're actually trying to achieve).
To do something with Float() on one line and avoid breaking code, use rescue as a statement modifier, as has been done in the is_number? method posted.
Float(string) rescue 0.0 # trying to emulate String#to_f!
Ensuring the phone number is 10 digits, numbers only, is quite simple.
PHONE_NUM_LENGTH = 10
string.length == PHONE_NUM_LENGTH && string.count('0-9') == PHONE_NUM_LENGTH
will return the true/false value representing this check. This is more efficient than a Regex.
The first part,
string.length == PHONE_NUM_LENGTH
checks whether the string is 10 characters long. The second,
string.count('0-9') == PHONE_NUM_LENGTH
checks whether it has exactly 10 numeric characters.

Lua: How to set a variable to zero

I have variable that contains a number. While Lua allows variables to be set to nil, the variable then becomes toxic - destroying all code in its path.
If a variable contains a nil, I want it converted to a zero.
local score;
score = gameResults.finalScore;
I want to ensure that score contains a number, so I try:
local score;
score = tonumber(gameResults.finalScore);
but that doesn't work. So I try:
local function ToNumberEx(v)
if (v == nil) then
return 0
else
return tonumber(v)
end
local score;
score = ToNumberEx(gameResults.finalScore);
but that doesn't work. So I try:
local function ToNumberEx(v)
if (v == nil) then
return 0
else
return tonumber(v)
end
local score;
score = ToNumberEx(gameResults.finalScore);
if (score == nil) then
score = 0
end
That works, but defeats the purpose of having a function.
What is wrong with the function? I'm sure there is a perfectly reasonable and logical explanation - except to anyone who is familiar with programming languages.
score = tonumber(gameResults.finalScore) or 0
If the argument is already a number or
a string convertible to a number, then
tonumber returns this number;
otherwise, it returns nil.
Your code was good, except you didn't take into account what happens when gameResult.finalScore can't be converted to a number, if it was " " or "stuff" or a table than tonumber would return nil. None of your checks could detect that kind of situation.
If you really want to enforce that this variable gameResults.finalScore has this behavior (set to zero when receives any value different from a number), than you should take a look at Lua metatables.
You could create a metatable for gameResults, and "overwrite" the "index" and "newindex" methods of the metatable, checking the value for the finalScore field, and thus enforcing it's value to be on the desired ranges.
Not the best solution, but depending on your case, could be a good defensive practice against some other "evil developer" on the team. :-)
www.lua.org/pil/13.html (I'm not currently allowed to post more than 1 link) PiL 1 can help too, if you are still using Lua 5.0 or you want a more deep understanding of the metatables concept.

Resources