lua-users home
lua-l archive

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


On 4/10/2012, at 1:14 AM, David Collier <myshkin@cix.co.uk> wrote:

> I suppose I could write a function "checkargs", and pass it the arguments
> and 1-byte statements of what they should be at the head of each routine.
> Then I can replace that routine with 'ret'
> 
> Or I can dig around for a Lua preprocessor, and try to work out how to
> tell eclipse to run it for me each time :-)

Or you could set a debug hook that parses LuaDoc-like comments and checks the arguments against them.  Then on your desktop you could go lua -lcheckargs myscript.lua, but leave out the -lcheckargs on your embedded system.

Here's a five-minute proof-of-concept:


function check_args(event)
local info = debug.getinfo(2, "Sn")
local source_file_name = info.source:match("@(.*)")
if source_file_name then
  local source_file = io.open(source_file_name, r)
  local lines = {}
  for i = 1, info.linedefined do
    lines[i] = source_file:read("*l")
  end
  local types = {}
  for i = info.linedefined - 1, 1, -1 do
    local t = lines[i]:match("%-%-%s*(.*)")
    if t then
      types[#types+1] = t
    else
      break
    end
  end
  for i = #types, 1, -1 do
    local name, value = debug.getlocal(2, #types - i + 1)
    if type(value) ~= types[i] then
      io.stderr:write(("Type of argument %d (%s) is a %s not a %s\n"):
        format(#types - i + 1, name, type(value), types[i]))
    end
  end
end  
end

debug.sethook(check_args, "c")


-- number
-- string
function a(n, s)
print(type(n), type(s))
end


a(1, "hello")
a("hello", 1)