[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: explicit mode
- From: Pierre-Yves Gérardy <pygy79@...>
- Date: Wed, 11 May 2016 11:45:30 +0200
On Tue, May 10, 2016 at 6:44 PM, Viacheslav Usov <via.usov@gmail.com> wrote:
> My policy is to guarantee that there are no problems related to mistyped
> identifiers. Not just this time I run my program, but every time I run it.
I use this as a file local equivalent to strict.lua. Works for Lua5.1 to 5.3
-- noglobals.lua
if pcall then
local function errR (_,i)
error("illegal global read: " .. tostring(i), 2)
end
local function errW (_,i, v)
error("illegal global write: " .. tostring(i)..": "..tostring(v), 2)
end
local env = {}
setmetatable(env, { __index=errR, __newindex=errW, __metatable=env })
return function()
pcall(setfenv, 3, env)
return env
end
else
return function()end
end
Then:
-- example.lua
local print = print
local noglobals = require'noglobals'
a = 5
local global = _ENV or _G -- if ever needed
local _ENV = noglobals()
-- from here on, global reads and writes trigger errors
print(global.a) -->5
print(a) --> Error: illegal global read: a
Is that better?
It requires pcall and setfenv, to work optimally and falls back as
gracefully as possible in their absence:
Lua 5.1: it becomes a noop
Lua 5.2+: less informative error messages
—Pierre-Yves