I'm coming to Lua from Python. I am using the Lua C API. I wonder if there is a standard method to bundle some parameter and usage information with the methods and tie it to a standard help() or <method>.__doc__()-like method.
Some ideas I had:
1) somehow put the docs in library metatable and let the users use pairs():
static const luaL_Reg lua_mylib_funcs[] = {
...
{NULL, NULL}};
2) print some usage info when the methods are called with no parameters.
3) create a .help() or a .docs() method for the library.
Can someone point in a "Lua-ish" direction?
I wonder if there is a standard method to bundle some parameter and usage information with the methods
Nope.
somehow put the docs in library metatable and let the users use pairs():
You could just establish a convention where if the method name is foo you store the docs in foo_docs or something like that.
x.foo_docs = "returns the sum of three numbers"
function x:foo(a,b,c)
return a + b + c
end
print some usage info when the methods are called with no parameters.
That would prevent you from creating methods with no parameters.
Can someone point in a "Lua-ish" direction?
Kinda hard to say without really know why you need it and how you'd prefer it to work. To get something like <method>.__doc__ you could convert a method (i.e. function) into a callable table, which would let you index it and store any metadata you want, but it would be ugly and require creating a new table per method. For instance, this would let you convert a method into a callable table:
local documentMethodMetatable = {}
function documentMethodMetatable.__call(t,...)
return t.method(...)
end
function documentMethod(method, doc)
return setmetatable({ method=method, doc=doc}, documentMethodMetatable)
end
Then you could write stuff like:
local foo = {name="Donut"}
function foo:sum(a,b,c)
print(self.name .. " says the sum is " .. (a + b + c))
end
foo.sum = documentMethod(foo.sum, "Receives three arguments and prints their sum.")
foo:sum(2,2,3) --> call sum
print(foo.sum.doc) --> index sum to get docs
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With