Page 1 of 1

[Solved] Am I overlooking something?

Posted: Wed Oct 29, 2014 4:00 am
by NutJob
Why does this work?

Code: Select all

function echoFunc()
	workdamnit("green")
end


function workdamnit(yyz)

		local yyzType = type(yyz)
		local a;
		if yyzType == "string" then
			print("it is a string")
			a = {}
			table.insert(a, yyz)
		end

	print(type(a))
end
######## RESULTS ##########
it is a string
table



And this does not work?

Code: Select all

function echoFunc()
	workdamnit("green")
end


function workdamnit(yyz)
	if yyz ~= nil then
		print("making headway")
		local yyzType = type(yyz)
		local a;
		if yyzType == "string" then
			print("it is a string")
			a = {}
			table.insert(a, yyz)
		end
	end
	print(type(a))
end
######## RESULTS ##########
making headway
it is a string

nil



I can really use some expertise on this, please.

Re: [Potential Bug] Am I overlooking something?

Posted: Wed Oct 29, 2014 5:25 am
by minmay
Since a is a local variable, it only exists inside its block. In the second example, you leave the block before calling type(a); since a is now out of scope, it is nil. To fix it, just move the declaration up:

Code: Select all

function workdamnit(yyz)
   local a
   if yyz ~= nil then
      print("making headway")
      local yyzType = type(yyz)
      if yyzType == "string" then
         print("it is a string")
         a = {}
         table.insert(a, yyz)
      end
   end
   print(type(a))
end

Re: [Potential Bug] Am I overlooking something?

Posted: Wed Oct 29, 2014 5:34 am
by NutJob
Thank you! Yes, it does work now.

This whole time I assumed the local keyword confined it to the function block and it didn't matter if it was inside a conditional block. Never once crossed my mind.

Again, thanks.