• Register

The near future: Trains are no longer controlled by humans. Instead, artificial intelligence is used to handle traffic. Program the best AI, beat challenges on various maps and watch it fight other AIs in live, online matches!

Forum Thread
  Posts  
declare global variable inside of functions? (Games : TrAInsported : Forum : General AI questions : declare global variable inside of functions?) Locked
Thread Options
Apr 23 2013 Anchor

ok, my code looks like this:

function ai.init(map,money)
   map1=map
   ---more script
end

for i=1, map1.height, 1 do
   ---some script
end

Now the error is, that map1 is only a local variable, and the error says, that 'map1' is a nil value.

Is there a way to bring the map variable outside the functions?

If i later do a

function ai.enoughMoney(money)
	buyTrain(random(map.width),random(map.height))
end

it works perfectly without an error, but why?

Apr 23 2013 Anchor

The way you declare it, map1 is a global value, just like you want it to be. The error is not in the creation but, if I see it right, then the for loop isn't just outside the ai.init function - it's outside of ALL functions.

If you have code outside of functions that code will be run when the file is first loaded, which happens before ai.init is called. This means that the for loop will be run when map1 is still unknown to Lua.

So make sure the for loop is inside a function (any function should do, as long as it's not called before the map1=map line is being run.
Example:

function ai.init(map,money)
   map1=map
   ---more script

   for i=1, map1.height, 1 do
      ---some script
   end
end

Or:

function ai.init(map,money)
   map1=map
   ---more script
end

function ai.chooseDirection()
   for i=1, map1.height, 1 do
      ---some script
   end
end
Apr 24 2013 Anchor

ah, i can see. Hm, i thought, when I could do my maths outside the function, I wouldn't fail at the time limit for ai.init() :S

ok, thank you for your answer

Apr 25 2013 Anchor

you can put the math in an extra function.

function doSomething()
do some math
end

Apr 25 2013 Anchor

yeah, but if i call a function from the ai.init(), the ai.init() will wait for my doSomething() function to end, so it still takes too long..

Apr 25 2013 Anchor

then you should think about optimizing ;)
Or doing less stuff...

Apr 25 2013 Anchor

yea, guess I have to... thanks for the answer

Reply to thread
click to sign in and post

Only registered members can share their thoughts. So come on! Join the community today (totally free - or sign in with your social account on the right) and join in the conversation.