如何在Lua中声明具有类型的变量

Dre*_*rew 4 oop variables lua types

是否可以在 Lua 中将变量创建为特定类型?

例如 int x = 4

如果这是不可能的,是否至少有某种方法可以在变量之前显示一个假的“类型”,以便任何阅读代码的人都知道变量应该是什么类型?

例如function addInt(int x=4, int y=5),但 x/y 仍然可以是任何类型的变量?我发现在它之前键入变量的类型比在函数上方放置注释来让任何读者知道它应该是什么类型的变量要容易得多。

我要求的唯一原因不是将变量限制为特定的数据类型,而只是为了能够将数据类型放在变量之前,无论它是否做任何事情,让读者知道是什么类型的它应该是没有错误的变量。

bam*_*s53 5

您可以使用评论来做到这一点:

local x = 4 -- int

function addInt(x --[[int]],
                y --[[int]] )
Run Code Online (Sandbox Code Playgroud)

您可以a = int(5)使用以下内容使其他评论中的语法起作用:

function int(a) return a end
function string(a) return a end
function dictionary(a) return a end

a = int(5)
b = string "hello, world!"
c = dictionary({foo = "hey"})
Run Code Online (Sandbox Code Playgroud)

尽管如此,这并没有真正为评论提供任何好处。


use*_*108 0

我能想到的唯一方法是在 C 中创建自定义类型。

Lua 整数类型