开发者

Is there a popular way to note types of variables and function arguments in Lua?

I'm finding a way to note开发者_JAVA技巧 types variables and function arguments in Lua. Is there a way? And any LINT-like tool to check those types?


I don't like encoding types on variable names. I prefer giving the variables explicit enough names so their intent is clear.

If I needed more than that, I use a typechecking function when needed:

function foo(array, callback, times)
  checkType( array,    'table',
             callback, 'function',
             times,    'number' )
  -- regular body of the function foo here

end

The function checkType can be implemented like this:

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

This has the advantage of properly raising an error on execution. If you have tests, your own tests will do the LINT-stuff and fail if a type is unexpected.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜