Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lua: How to set a variable to zero

Tags:

casting

lua

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.

like image 656
Ian Boyd Avatar asked Nov 29 '22 18:11

Ian Boyd


1 Answers

score = tonumber(gameResults.finalScore) or 0
like image 132
Noah Witherspoon Avatar answered Feb 16 '23 03:02

Noah Witherspoon