There was some discussion about type checking in the LuaOhSix
workshop. I've now experimented with the concept (at a patch
level, on 5.1.1) and come to the point where it's better to stop
for a while, and tell what I've been up to.
Here are syntactic samples, they do parse but don't get runtime-
checked, yet (there's a couple greater hurdles on that..)
-- -1<=v<=3 on input, and -2<= <=2 on return
--
local function mynut( v :range(-1,3) )
: range(-2,2)
return v-1
end
-- more parameters, multiple return types
--
local function mydear( t :string_or_table, i :int, j :int_opt,
n :number_opt )
: string : table : int_opt
--return -- fail
--return 1,2,3 --fail
--return "",{i=5} -- ok
return "",{i=5},33 -- ok
end
-- table structure constraint (can also be covered by a custom
constraint function)
--
local myfear= function( t :{ a=int, b=string }, v :int_opt )
..
end
local function myfear( t :myab, v :int_opt )
..
end
I first planned only to have the function entry/return values
checked (and this can be done in pure Lua, it's not much trouble..)
but later extended to concept to what if _any_ Lua (local) variable
could be tagged as of certain type(s), and that tested each time
the variable is given a new value.
local myvar :int, mystr :string= 10, 0 -- will become "0"
assert.number( myvar )
assert.string( mystr ) -- mystr should have implicitly gotten 0-
>"0" conversion
One could use such technique only where wanting, of course. The
purpose would be to bring Lua a bit towards the static typed
direction, but carefully.
There are some neat side-effects to this. :) Such as ability to
implicitly make those '(%d+)' captures become numbers, without
harming the rest of the Lua population. That was not why I started
to look into this, though.
local a:number, b:any= string.match( "123 456", "^(%d+)%s+(%d+)" )
Will finish this "sometime later". Currently, it's here just to
let you know, and in case someone's up to a similar study.
- asko
<sample.lua>