我正在寻找一种方法来记录 Lua 中的类型变量和函数参数。有办法吗?以及任何类似 LINT 的工具来检查这些类型?
问问题
94 次
1 回答
3
我不喜欢变量名的编码类型。我更喜欢给变量足够明确的名称,这样它们的意图就很清楚了。
如果我需要更多,我会在需要时使用类型检查功能:
function foo(array, callback, times)
checkType( array, 'table',
callback, 'function',
times, 'number' )
-- regular body of the function foo here
end
该功能checkType
可以这样实现:
function checkType(...)
local args = {...}
local var, kind
for i=1, #args, 2 do
var = args[i]
kind = args[i+1]
assert(type(var) == kind, "Expected " .. tostring(var) .. " to be of type " .. tostring(kind))
end
end
这具有在执行时正确引发错误的优点。如果你有测试,你自己的测试会做 LINT-stuff,如果类型是意外的,就会失败。
于 2011-06-11T09:37:15.693 回答