This repository was archived by the owner on Jul 11, 2026. It is now read-only.
forked from darrellanderson/CrLua
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLockGlobals.ttslua
More file actions
50 lines (42 loc) · 1.86 KB
/
Copy pathLockGlobals.ttslua
File metadata and controls
50 lines (42 loc) · 1.86 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
-------------------------------------------------------------------------------
--- Partially lock the _G global variable table.
-- Include this AFTER creating any necessary globals to prevent new ones.
--
-- - Existing globals can still be read AND WRITTEN.
-- - Cannot read non-existent globals.
-- - Cannot write new globals.
--
-- This helps catch typos where what was meant to access a local instead
-- references a (hopefully non-existent) global, as well as forgetting to use
-- "local" when creating objects.
--
-- @author Darrell
-------------------------------------------------------------------------------
local TAG = 'CrLua.LockGlobals'
local _lockGlobalsMetaTable = {}
-- Index is only called when the key does not already exist.
function _lockGlobalsMetaTable.__index(table, key)
error(TAG .. ': accessing missing global "' .. tostring(key or '<nil>') .. '", typo?', 2)
end
function _lockGlobalsMetaTable.__newindex(table, key, value)
error(TAG .. ': globals are locked, cannot create global variable "' .. tostring(key or '<nil>') .. '"', 2)
end
setmetatable(_G, _lockGlobalsMetaTable)
-------------------------------------------------------------------------------
-- Add a test function to the CrLua "namespace".
CrLua = CrLua or {} -- global, <include> wraps in a do .. end block
CrLua.LockGlobals = assert(not CrLua.LockGlobals) and {
_require = { 'LockGlobals' } -- require self to avoid missing require error
}
function CrLua.LockGlobals._testLockGlobals()
-- Can read existing global.
assert(_VERSION)
-- Cannot read missing global.
if pcall(function() return thisGlobalVariableDoesNotExistHopefully end) then
error('was able to write missing global')
end
-- Cannot write missing global.
if pcall(function() thisGlobalVariableDoesNotExistHopefully = 1 end) then
error('was able to write missing global')
end
end