Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lua "require" with global "local"?

Clearly I have some mixed up, but I figured that by using something like this in "main.lua":

local module = require("module")
local var = "I should be global?"
printthis()

with module.lua containing something like:

function printthis()
    print(var)
end

that printthis(var) would work fine, because now the module.lua code is inside main.lua, no? Instead, printthis has no idea what var is. I read it's good practice to use "local" on Lua variables when possible, but in this case, do I have to make var global or is there a way for module.lua's printthis() function to read var properly?

like image 904
Brian Avatar asked Jul 05 '11 16:07

Brian


1 Answers

No. That's not at all how it works.

The Lua interpreter provides one global table, referred to as _G normally, unless you're doing something kinky.

function printthis()
    print(var)
end

This translates to, in reality

_G.printthis = function()
    _G.print(_G.var);
end

And your code in main is equal to

local module = _G.require("module")
local var = "I should be global?"
_G.printthis()

But when you call printthis- where did _G.var get set? Nowhere. So the variable is nil, like all other accesses to a table where there is nothing at that key.

It might be inconvenient, but it's a much better idea in the long run to pass arguments than to set global variables instead. Once you come to change anything about the program, it's going to be completely impossible to make any changes, as the logic has no structure and you have no idea what happens where without reading every single line of code and understanding it at once. In addition, you can only use each key in one place, because it's a global table- so I sure hope nobody else wanted to use "var" as a variable name and you don't mind your code silently failing because you got a global name wrong.

like image 112
Puppy Avatar answered Oct 14 '22 08:10

Puppy