lua-users home
lua-l archive

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


> The problem is with Lua-based DSLs, which are IMO a fantastic tool. With a
> "global" declaration enforcement rule, they'll become a pain.
>
> This is a place where some customization/parametrization of the compilation
> process would come handy.

In vanilla Lua you can alter the Metatable of _G to signal
unreferenced use and creation. So one can alter this global by default
behavior to fit to something less error-prone. If you need to create a
 syntax to create a global nevertheless is just a little more ugly, as
you need to call a custom function, but I dont need that. In my
projects, after an initial startupphase I run:

local function lockGlobals()
    local t = _G
    local mt = getmetatable(t) or {}
    mt.__index = function(t, k)
        if (k~="_" and string.sub(k, 1, 2) ~= "__") then
            error("Access of non-existing global '"..k.."'", 2)
        else
            rawget(t, k)
        end
    end
    mt.__newindex = function(t, k, v)
        if (k~="_" and string.sub(k, 1, 2) ~= "__") then
            error("This project does not allow GLOBALS to be created
on the fly. " ..
                  "Declare '" ..k.."' local or declare global on load.", 2)
        else
            rawset(t, k, v)
        end
    end
    setmetatable(t, mt)
end

so no more Globals after that, and any type results in an error where
the typo occured.

As far as I can see, moonscript takes that ability (like Coffeescript)
from me, as it has no longer a "local" or "global" keyword, and
declares variables global/local depending if the parser already knows
about them or not.