andremm / typedlua

An Optional Type System for Lua
565 stars 53 forks source link

Access records with supertypes of literal index type #92

Closed Veltas closed 8 years ago

Veltas commented 8 years ago

With table types defined for literal indices, quite often I still want to access elements with a supertype of the index type.

For example

local r = {a = 1, b = 2}
local i = 1
print(r[i]) -- error, attempt to index '{"a": integer, "b": integer}' with 'integer'

But it has occurred to me the worst that could happen accessing incorrectly is producing a nil, as long as I don't try to set with non-literals I'm not doing anything wrong.

Consider the following: I is a supertype of literal type L. We have a table r: {L: X} for some type X. Then for a value i: I, the expression r[i] is valid and has type X|nil.

I propose the language allow this type of access, if possible.

Veltas commented 8 years ago

In case people come to this and wonder why I closed it, read the Typed Lua paper: it explains this kind of relation between types is unsound, so this would have to be a special case and probably kind of dirty.