1
0

Added 'strict tables', that throw very informative errors, when indexing an non-existant key.

This commit is contained in:
Jon Michael Aanes 2017-07-10 10:14:46 +02:00
parent 0fbea038a7
commit 57ddbbf62f
3 changed files with 30 additions and 0 deletions

View File

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

View File

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

View File

@ -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()