Page 1 of 1

Scoping issues in Lua while tidying code

Posted: Wed Nov 02, 2016 4:55 pm
by Madrayken
Hi folks,
I'm in the midst of a new Löve project and trying to use fewer globals this time around. :-)

As such, I've made my modules something along the lines of this:

Code: Select all

local module = {}
local a = 0

local function doThing()
	print("Hello")
	a = 5
end

module.a = a
module.doThing = doThing

return module
In my main.lua:

Code: Select all

local mod = require("module")
function love.load()
	mod.doThing()
	print(mod.a)
end
The result I get is:

Code: Select all

"Hello"
0
This is presumably because 'require' gave me an 'old' version of module.a, and the newer version has not been assigned? As such, this is clearly the wrong way to get module variables.

I could always grab them as a table via a function, I suppose, but is there a more elegant way to expose variables like this?

Re: Scoping issues in Lua while tidying code

Posted: Wed Nov 02, 2016 5:05 pm
by kikito
Hi. Congratulations on trying to improve the number of globals you use.

There is an easy fix for your situation: instead of using a "local inside the file", use a "table attribute", like so:

Code: Select all

local module = {}

module.a = 0

module.doThing = function()
   print("Hello")
   module.a = 5
end

return module

(Notice that module is a reserved word in Lua, I recommend using something else :))

However, please note that your "a" attribute is still a global variable, in a way. It's namespaced inside a module, which is better than being a "completely global" variable, but it still means that your library holds global state. I explain how to overcome that here: http://kiki.to/blog/2014/04/11/rule-4-m ... s-modules/

Re: Scoping issues in Lua while tidying code

Posted: Wed Nov 02, 2016 5:55 pm
by Madrayken
Thanks so much for the clarification. It's super obvious, so can't believe I didn't think of that, considering how much lua code I've looked at!

As for 'module' being a reserved word: ahahahahaha... I'd forgotten that. Luckily that was just a demo piece of code for here, not my actual project.

Re: Scoping issues in Lua while tidying code

Posted: Wed Nov 02, 2016 6:11 pm
by ivan
Also, check out the strict.lua module:
http://metalua.luaforge.net/src/lib/strict.lua.html
Which raises an error whenever your code tries to access 'undeclared' global variables.