gpt4 book ai didi

types - 类型检查不适用于 Luau 中的通用字符串键?

转载 作者:行者123 更新时间:2023-12-05 04:24:12 24 4
gpt4 key购买 nike

我正在尝试创建一个字典数据结构,其中包含多个可以与任何字符串键关联的 CustomType 对象。

我想我可以使用 {[string]: CustomType} 作为我的字典类型,像这样:

--!strict
type CustomType = {
a: string,
b: string
}

local dictionary: {[string]: CustomType} = {
keyOne = { a = 'hello' }, -- should display type error ('b' field missing)
keyTwo = { a = 'hello', b = 'world'} -- should be fine
}

但是,在上面的代码片段中,即使 keyOne 中缺少 b 字段,代码编辑器中也没有显示类型错误。然而,如果我在字典类型定义中明确定义键,那么它会按预期工作:

--!strict
type CustomType = {
a: string,
b: string
}

local dictionary: {keyOne: CustomType, keyTwo: CustomType} = {
keyOne = { a = 'hello' }, -- displays type error
keyTwo = { a = 'hello', b = 'world'} -- is fine
}

这是为什么? 我想对所有通用字符串键执行严格的类型检查,而无需在字典类型定义中明确定义它们。我这样做的方式是否错误?这可能是 ROBLOX 问题(因为我正在 ROBLOX 引擎中实现它)?

如有任何帮助,我们将不胜感激。

关于 Luau 类型检查的来源/信息:https://luau-lang.org/typecheck

最佳答案

不幸的是,在当前的 Luau 中(截至 2022 年 9 月撰写本文时为 0.545),一旦您的类型中有索引器([string]),该类型上的其余键将不会以您期望的方式进行检查。

与显式方法调用相比,使用索引器绝对是一个很好的人体工程学改进,但除了类型系统在这些情况下不能完全提供您想要的安全性之外,它有时可能比显式方法调用方法。

为了更好的人体工程学而覆盖表上的 __index、__newindex 和/或 __call 时,请确保您不会在不知不觉中选择退出类型安全,或增加 Luau 应用程序热路径中的运行时开销。

关于types - 类型检查不适用于 Luau 中的通用字符串键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73558671/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com