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 you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With