Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

Is there any use for global variables in Lua?

Asked by
cabbler 1942 Moderation Voter
6 years ago

As in whether to put "local" before declarations; not _G. Internally locals are indexed in arrays rather than dictionaries, so even at global scope it is more efficient to make everything local. I would love an argument otherwise

0
I'd say a good example is for when something doesn't go right. E.x. Check if an item exist, like a folder. Folder isn't found, redefine the value to a new folder (via Instance.new) TheeDeathCaster 2368 — 6y
0
local folder = [Wherever] if not folder then folder = [New Folder] end TheeDeathCaster 2368 — 6y
0
??? cabbler 1942 — 6y

2 answers

Log in to vote
0
Answered by 6 years ago

Ease of access. I would say _G. is risky to use because Roblox is finicky, but _G. would be useful if you're trying to exchange VERY simple data. If you want to get fancy with your functions, i recommend the Modules.

0
Sorry not talking about _G cabbler 1942 — 6y
Ad
Log in to vote
0
Answered by 6 years ago

I think you can always use local variables and still have a functioning script. One way to, I guess, "bypass" global variables is by using an upvalue. e.g.

--script with global variable, no upvalue
function abc()
    var = true --probably a warning because you used a global variable
end
function def()
    var = false
end
--script with upvalue
local var --sets it to nil; can still be set inside of inner scopes
function abc()
    var = true --no warning since the var is local to the scope above this
end
function def()
    var = false
end

You can live without global variables.

0
Ye any 'global' implementation can be fixed with more reasonable scoping. So you agree? cabbler 1942 — 6y

Answer this question