I've found that test-driven development is the fastest way for me to learn a new language. There is no better way to bootstrap the learning process than by figuring out how to cobble together a minimal expectation-based testing framework in the new language. The following is the result of my first hour with Lua.
-- #t behaves strangely with hashtables & nil values | |
function table_length(t) | |
local count = 0 | |
for _ in pairs(t) do count = count + 1 end | |
return count | |
end | |
function Test(test, expectation) | |
return { | |
test = test, | |
expectation = expectation, | |
run = function(self) | |
local result = self.test() | |
return self.expectation(result) | |
end | |
} | |
end | |
function TestSuite(tests) | |
return { | |
run = function(self) | |
print("Running test suite...") | |
local failed_tests = {} | |
for k,v in pairs(self.tests) do | |
local outcome = v:run() | |
if outcome then | |
io.write(".") | |
else | |
io.write("-") | |
failed_tests[k] = outcome | |
end | |
end | |
print("") | |
local failed_count = table_length(failed_tests) | |
if failed_count > 0 then | |
print(failed_count.." failed test(s): ") | |
for k,v in pairs(failed_tests) do | |
io.write(k.." ") | |
end | |
print("") | |
else | |
print("Success!") | |
end | |
end, | |
tests = tests | |
} | |
end | |
tests = { | |
simple = Test( | |
function() | |
return 5 | |
end, | |
function(result) | |
return result == 5 | |
end | |
) | |
} | |
TestSuite(tests):run() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment