Skip to content

Instantly share code, notes, and snippets.

@mrange
Last active November 24, 2024 14:06
Show Gist options
  • Save mrange/2a0b227083ed5f4526589d02da27a351 to your computer and use it in GitHub Desktop.
Save mrange/2a0b227083ed5f4526589d02da27a351 to your computer and use it in GitHub Desktop.
Strict mode in LUA
-- The strict() function helps catch common Lua programming errors
-- by detecting uses of undefined variables. This is helpful because
-- Lua normally creates global variables silently when you mistype
-- a variable name, which can lead to hard-to-find bugs.
function strict()
local declared_globals = {}
-- In Lua, _G is a special table that holds all global variables
-- setmetatable lets us intercept attempts to read or write globals
setmetatable(_G, {
-- This function is called when code tries to create a new
-- global variable. We make it throw an error instead of
-- silently creating the variable.
__newindex = function(_, name, value)
if not declared_globals[name] then
error("Attempt to create global variable '" .. name .. "'", 2)
end
rawset(_G, name, value)
end,
-- This function is called when code tries to read a global
-- variable. We log a warning if the variable doesn't exist.
-- Note: We can't crash here because TIC-80 constantly checks
-- for certain global functions it needs to run.
__index = function(_, name)
if not declared_globals[name] then
trace("Attempt to access undeclared global variable '" .. name .. "'", 2)
end
return nil
end
})
end
function TIC()
-- Will throw if strict is enabled
x = 3
end
function BOOT()
-- Enable strict mode
strict()
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment