diff --git a/errors.lua b/errors.lua index 63cd7d0..c2b8ae2 100644 --- a/errors.lua +++ b/errors.lua @@ -139,5 +139,17 @@ return function (module_name) end end + function err_hdl.strict_table (...) + local args = {...} + if args[1] == err_hdl then table.remove(args, 1) end + return setmetatable(args[1] or {}, { + __index = function (t, k) + local keys = {} + for k in pairs(t) do keys[#keys+1] = k end + correct_error(err_hdl, '', 'Attempting to index unknown key %s, maybe you meant %s?', k, keys) + end + }) + end + return err_hdl end diff --git a/test/test_errors.lua b/test/test_errors.lua index 637f50f..41757a9 100644 --- a/test/test_errors.lua +++ b/test/test_errors.lua @@ -92,6 +92,23 @@ SUITE:addTest('Correct errors has nice default string', function() assert_equal(expected_error, err_msg) end) +-------------------------------------------------------------------------------- +-- Strict table + +SUITE:addTest('Strict tables can be accessed normally', function() + local t = error.strict_table { a = 1, b = 2, c = 3 } + assert(t.a, 1) + assert(t.b, 2) + assert(t.c, 3) +end) + +SUITE:addTest('Strict tables throw errors on unknown indices', function() + local t = error.strict_table { a = 1, b = 2, c = 3 } + bad_call(function() return t.hello end) +end) + + + -------------------------------------------------------------------------------- return SUITE diff --git a/test/tests.lua b/test/tests.lua index 5890d0f..e57d156 100644 --- a/test/tests.lua +++ b/test/tests.lua @@ -2,6 +2,7 @@ package.path = package.path .. ';./test/?.lua;./src/?.lua' local TEST_SUITE = require 'TestSuite' 'errors' + --TEST_SUITE:enableStrictGlobal() TEST_SUITE:addModules 'test/test_*' TEST_SUITE:setOptions(...) TEST_SUITE:runTests()