[Solved] Am I overlooking something?

Ask for help about creating mods and scripts for Grimrock 2 or share your tips, scripts, tools and assets with other modders here. Warning: forum contains spoilers!
Post Reply
NutJob
Posts: 426
Joined: Sun Oct 19, 2014 6:35 pm

[Solved] Am I overlooking something?

Post 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.
Last edited by NutJob on Wed Oct 29, 2014 5:35 am, edited 1 time in total.
minmay
Posts: 2790
Joined: Mon Sep 23, 2013 2:24 am

Re: [Potential Bug] Am I overlooking something?

Post 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
Grimrock 1 dungeon
Grimrock 2 resources
I no longer answer scripting questions in private messages. Please ask in a forum topic or this Discord server.
NutJob
Posts: 426
Joined: Sun Oct 19, 2014 6:35 pm

Re: [Potential Bug] Am I overlooking something?

Post 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.
Post Reply