Page 4 of 4

Re: Lua local question

Posted: Mon Aug 22, 2011 4:20 pm
by tentus
In Kurosuke, I require "scenes" from the main file, the first of which has this line in it:

Code: Select all

require "subclass/startup"
This startup file has tons of variable like this in it:

Code: Select all

currentLevel = "level_1"
multiplayer = 1
players = {}
Most of these variables don't get mentioned again until we're two more scenes into the game (ie, two more requires deep).

If a variable is not defined as local, it is global to the entire game. It doesn't matter which file it is defined in. Think in terms of functions, not files.

Edit: following statement is false, apparently.
So, if you want a variable to be local to a file, you have to make sure that file's contents are inside a big function, otherwise it is effectively global again (it's effectively local will refer to the whole program, if I remember correctly).

Re: Lua local question

Posted: Mon Aug 22, 2011 6:13 pm
by T-Bone
Okay, I get it :neko:

Re: Lua local question

Posted: Mon Aug 22, 2011 10:58 pm
by Robin
tentus wrote:So, if you want a variable to be local to a file, you have to make sure that file's contents are inside a big function, otherwise it is effectively global again (it's effectively local will refer to the whole program, if I remember correctly).
No.

Lua is fully lexically scoped, which means that:

Code: Select all

local this = true
for i = 1, 1 do
   local this = false
   print(this) -- prints false
end
print(this) -- prints true
A file is compiled down to a "chunk", just like functions are.
If you have a file called a.lua:

Code: Select all

local jazz = 5
And a main.lua:

Code: Select all

require 'a'
print(jazz) -- prints nil

Re: Lua local question

Posted: Mon Aug 22, 2011 11:19 pm
by tentus
Robin wrote:
tentus wrote:So, if you want a variable to be local to a file, you have to make sure that file's contents are inside a big function, otherwise it is effectively global again (it's effectively local will refer to the whole program, if I remember correctly).
No.

Lua is fully lexically scoped, which means that:

Code: Select all

local this = true
for i = 1, 1 do
   local this = false
   print(this) -- prints false
end
print(this) -- prints true
A file is compiled down to a "chunk", just like functions are.
If you have a file called a.lua:

Code: Select all

local jazz = 5
And a main.lua:

Code: Select all

require 'a'
print(jazz) -- prints nil
Huh. I don't recall that behavior, but I guess that shows how little I use inter-file variables that don't need to be global.