lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


>  > LuaSub gives '-sjacket' for making runtime type checks, and it works
>  > like this:
>  >
>  > tests/test-jacket.lua:
>  >
>  > local function mydear( t :string_or_table, i :int, j :[int], n :
>  > [number] )
>  >    : string, table, [int]
>  > ...function body with returns...
>  > end
>  >
>  > 't' is either string or table (checked by 'assert.string_or_table()')
>  > 'i' is integer ('assert.int()')
>  > 'j' is an optional integer (nil or fulfilling 'assert.int()')
>  > 'n' is ...
>
>  It's interesting syntactic sugar. Obviously this could be handled by
>  assertions in the code but sugar might increase the chance that they would
>  get written.

We heavilly use argument type validation in our engine-level Lua
function (that is, written by experienced programmers, not by end-user
scriptors).

Like this (silly example):

local string_rep = function(s, n)
  n = n or 1
  assert_is_string(s) -- basically a wrapper on assert(type(s) == "string")
  assert_is_number(n)

  if n > 1 then
    local t = {}
    for i = 1, n do
      t[i] = s
    end
    s = table.concat(t)
  end
  return s
end

Actually most of our code have such type checks.

When I saw this post by David Manura on decorators in Lua,

http://lua-users.org/lists/lua-l/2007-09/msg00271.html

I thought of implementing something along these lines:

local string_rep =
  docs
  [[Returns a string that is the concatenation
  of n copies of the string s.]] ..
  args { 'string', optional 'number' (1) } ..
  rets { 'string' } ..
  function (s, n)
    if n > 1 then
      local t = {}
      for i = 1, n do
        t[i] = s
      end
      s = table.concat(t)
    end
    return s
  end

This could allow writing inplace function documentation (suitable for
run-time help) and call contract validation (arguments, preconditions,
return values, postconditons) in plain Lua. Also suitable to ease
automatical code instrumentation for, say, call tracing or profiling
etc..

Contract validation functions could be pre-generated on the
initialization time. Also it should not be hard to skip all those
calls in 'release' version of Lua scripts (just generate them as
no-ops).

Still have to find some time to actually try this though. :-)

Alexander.