-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathex25.2.lua
More file actions
83 lines (78 loc) · 1.96 KB
/
ex25.2.lua
File metadata and controls
83 lines (78 loc) · 1.96 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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
local function getvarvalue (name, level, isenv)
local value
local found = false
level = (level or 1) + 1
-- try local variables
for i = 1, math.huge do
local n, v = debug.getlocal(level, i)
if not n then break end
if n == name then
value = v
found = true
end
end
if found then return "local", value end
-- try non-local variables
local func = debug.getinfo(level, "f").func
for i = 1, math.huge do
local n, v = debug.getupvalue(func, i)
if not n then break end
if n == name then return "upvalue", v end
end
if isenv then return "noenv" end
-- avoid loop
-- not found; get value from the environment
local _, env = getvarvalue("_ENV", level, true)
if env then
return "global", env[name]
else
-- no _ENV available
return "noenv"
end
end
local function setvarvalue (name, value, level, isenv)
local found = false
local old_value
level = (level or 1) + 1
-- try local variables
for i = 1, math.huge do
local n, v = debug.getlocal(level, i)
if not n then break end
if n == name then
old_value = v
debug.setlocal(level, i, value)
found = true
end
end
if found then return "local", old_value end
-- try non-local variables
local func = debug.getinfo(level, "f").func
for i = 1, math.huge do
local n, v = debug.getupvalue(func, i)
if not n then break end
if n == name then
debug.setupvalue(func, i, value)
old_value = v
return "upvalue", old_value
end
end
if isenv then return "noenv" end
-- avoid loop
-- not found; get value from the environment
local _, env = getvarvalue("_ENV", level, true)
if env then
old_value = env[name]
env[name] = value
return "global", old_value
else
-- no _ENV available
return "noenv"
end
end
x = 100
local f = function ()
x = 50
print(setvarvalue("x", 200))
end
f()
print(x)