math not working

I don’t understand how I can set a value month to 1 and my first print statement shows 1 and then my third print statement shows the value as nil
local yr = tonumber(_G[“yr”])

if tonumber(_G[“mo”]) == nil then
local month = 1
print("i am here month "…tostring(month))

else
local month = tonumber(_G[“mo”])
end

if tonumber(_G[“da”]) == nil then
local day = 1
print("i am here "…tostring(day))
else
local day = tonumber(_G[“da”])
end

if yr < 1583 then
local g = 0
else
local g = 1

end

local d1 = day

local f = - .5

local j = 0
print("month is "…tostring(month))
j = month
Any ideas? [import]uid: 136344 topic_id: 26395 reply_id: 326395[/import]

Never mind. I doesn’t make sense that if I move the local out of the if statement it works. [import]uid: 136344 topic_id: 26395 reply_id: 107036[/import]

It makes sense, but you need to understand Lua’s variable scoping first. Local variables are only available to the code block in which they’re defined. [import]uid: 44647 topic_id: 26395 reply_id: 107039[/import]

You have a “Scope” problem.

When you declare a variable inside a block (or chunk in Lua terms) like:

if condition then  
 local somevar = 1  
end  

that variable is only “in scope” or defined within that block.

You need to do this:

local month = 1  
if tonumber(\_G["mo"]) ~= nil then  
 month = tonumber(\_G["mo"])  
end  
  

See: http://omnigeek.robmiracle.com/2011/10/14/understanding-scope-for-beginning-programmers/

[import]uid: 19626 topic_id: 26395 reply_id: 107040[/import]

Thanks for your help. [import]uid: 136344 topic_id: 26395 reply_id: 107092[/import]