lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]

On Tue, May 10, 2016 at 6:44 PM, Viacheslav Usov <> 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)
        local function errW (_,i, v)
            error("illegal global write: " .. tostring(i)..": "..tostring(v), 2)
        local env = {}
        setmetatable(env, { __index=errR, __newindex=errW, __metatable=env })

        return function()
            pcall(setfenv, 3, env)
            return env
        return function()end


    -- 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