lua-users home
lua-l archive

Re: Implementing help function (like in Python)

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


Matias Guijarro wrote:
I would like to implement...like Python docstrings...
> I think a possible solution would be to use the debug library
> (debug.getinfo) to find the source file and to extract a kind of
> "docstring" out of the function code.
This can be done using weak tables in a way that avoids source processing and debug:
-- docstring.lua
local M = {}
local docstrings = setmetatable({}, {__mode = 'kv'})
function M.set(obj, str)
 docstrings[obj] = str
 return obj
end
function M.get(obj) return docstrings[obj] end
function M.help(obj) print(M.get(obj)) end
-- optional syntax simplification
local mt = {__concat = function(self, obj)
 return M.set(obj, self[1]) end}
setmetatable(M, {__call = function(_, str)
 return setmetatable({str}, mt)
end})
return M
-- test.lua (example)
local docstring = require 'docstring'
local square =
 docstring[[Square a number.]] ..
 function(x)
 return x * x
 end
assert(square(5) == 25)
assert(docstring.get(square) == 'Square a number.')
docstring.help(square) -- prints "Square a number."
docstring.set(square, 'calcular el cuadrado de un número')
assert(docstring.get(square) == 'calcular el cuadrado de un número')
assert(docstring.get(print) == nil)
One reason '..' is chosen is because it is right associative, which allows additional decorators (besides docstrings) to be applied to an object as well.

AltStyle によって変換されたページ (->オリジナル) /