3 ms·
Something like function no_globals() setmetatable(_G, { __newindex = function(t, k, v) return error("attempt to set global '"..tostri
by dividuum 6y ago
Something like
function no_globals()
setmetatable(_G, {
__newindex = function(t, k, v)
return error("attempt to set global '"..tostring(k))
end,
__index = function(t, k)
return error("attempt to reference missing global '"..tostring(k))
end,
})
end
can help catch assignment and usage of undefined (e.g. by not using 'local') variables. The downside is that this then also applies to function definitions. So be prepared to write 'local function xyz()'.
- TulliusCicero 6y agoPeople keep pointing out workarounds to me. Thanks, but that's not really what I'm getting at. My complaint is that, if the language is supposed to be good for beginners, the workarounds should be unnecessary, since beginners are unlikely to a) be able to find proper workarounds, or b) even be aware that there's a problem that a workaround would be needed to solve. My son has no idea that invoking an un-initialized global variable immediately brings it into being with 'nil' is weird behavior for a language. If a less experienced programmer was the one helping him learn, they might not realize it either.
- samatman 6y agoAs I said in a sibling comment, Lua isn't designed to be good for beginners, it's simple rather than easy. But I want to stand up for this, in particular. Because in most languages, environments are magic: they're an exceptional thing that you work with in a special way, you're not expected to understand them, just use them. In Lua, an environment is... just a table! You can set an environment, read from it directly, assign it a metatable, and so on. So this is great for a beginner, once he gets past the hurdle. Just like `table.field` returns `nil` if there's no field field, `field` itself returns nil if there's no `_G.field`. Because _G.field and field itself are the same thing.
- TulliusCicero 6y ago> So this is great for a beginner, once he gets past the hurdle. Is it? Because that still seems very error prone to me. You're not gonna suddenly stop making typos just because you understand that there's an invisible global table around all the time. But hey, maybe it's super awesome later on, though I'm having trouble imagining scenarios where this behavior is all that useful over what most other languages do.