Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
COMMUNITY QUESTION

Is there any use for global variables in Lua?

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

3 comments

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)

0

local folder = [Wherever] if not folder then folder = [New Folder] end

0

???

2 answers

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.

1 comment

0

Sorry not talking about _G

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.

1 comment

0

Ye any 'global' implementation can be fixed with more reasonable scoping. So you agree?

This discussion is preserved as it was. New answers, comments, and votes are closed.