Lua 中有没有一种流行的方法来记录变量和函数参数的类型?

发布于 2024-11-15 02:45:39 字数 63 浏览 5 评论 0原文

我正在寻找一种方法来记录 Lua 中的类型变量和函数参数。有办法吗?还有类似 LINT 的工具来检查这些类型吗?

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

夜光 2024-11-22 02:45:39

我不喜欢变量名称的编码类型。我更喜欢给变量提供足够明确的名称,这样它们的意图就很清楚。

如果我需要更多,我会在需要时使用类型检查函数:

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 操作,如果类型不符合预期,则测试会失败。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文