Debian Codegraph @

CorsixTH/Luatest/non_strict.lua

raw
1 --[[ Copyright (c) 2014 Edvin "Lego3" Linge
2
3 Permission is hereby granted, free of charge, to any person obtaining a copy of
4 this software and associated documentation files (the "Software"), to deal in
5 the Software without restriction, including without limitation the rights to
6 use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
7 of the Software, and to permit persons to whom the Software is furnished to do
8 so, subject to the following conditions:
9
10 The above copyright notice and this permission notice shall be included in all
11 copies or substantial portions of the Software.
12
13 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
19 SOFTWARE. --]]
20
21 -- When running unittests we cannot restrict global variables as is usually
22 -- done, since the busted library relies on being able to do so.
23 -- We still need to mimic the possibility to call the functions available
24 -- in strict.lua though.
25
26 local strict_mt = {}
27 local allowed_globals = setmetatable({}, {__mode = "k"})
28
29 local function newindex(t, k, v)
30 rawset(t, k, v)
31 end
32
33 local function index()
34 return nil
35 end
36
37 local function restrict(ni, i, ...)
38 strict_mt.__newindex = ni
39 strict_mt.__index = i
40 return ...
41 end
42 restrict(newindex, index)
43
44 --!! Wrap a function so that it is freely able to set global variables
45 --[[ Some existing functions (for example, `require`) should be allowed to read
46 and write global variables without having to worry about declaring them
47 with `strict_declare_global`.
48 !param fn The function which should be able to freely set globals
49 !return A new function which acts just as `fn` and is free to set globals
50 !example
51 require = destrict(require) ]]
52 function destrict(fn)
53 return function(...)
54 local ni, i = strict_mt.__newindex, strict_mt.__index
55 strict_mt.__newindex, strict_mt.__index = nil, nil
56 return restrict(ni, i, fn(...))
57 end
58 end
59
60 --!! Declare a global variable so that it can later be used
61 --[[!param name The name of the global to declare
62 !example
63 strict_declare_global "some_var"
64 some_var = 42 ]]
65 function strict_declare_global(name)
66 allowed_globals[name] = true
67 end
68
69 setmetatable(_G, strict_mt)