reflection - Lua - 反射 - 函数参数和文档字符串?

标签 reflection lua

我从 Python 来到 Lua。我正在使用 Lua C API。我想知道是否有一种标准方法可以将一些参数和使用信息与方法捆绑在一起,并将其绑定(bind)到标准 help()<method>.__doc__() ——类似的方法。

我的一些想法:

1) 以某种方式将文档放入元表库中,让用户使用pairs() :

static const luaL_Reg lua_mylib_funcs[] = {
    ...
    {NULL, NULL}};

2) 在无参数调用方法时打印一些使用信息。

3)创建一个.help().docs()库的方法。

有人可以指出“Lua-ish”的方向吗?

最佳答案

I wonder if there is a standard method to bundle some parameter and usage information with the methods



没有。

somehow put the docs in library metatable and let the users use pairs():



如果方法名称是 foo,您可以建立一个约定。您将文档存储在 foo_docs或类似的东西。
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.



这将阻止您创建没有参数的方法。

Can someone point in a "Lua-ish" direction?



如果不知道您为什么需要它以及您希望它如何工作,这很难说。得到类似 <method>.__doc__ 的东西您可以将方法(即函数)转换为可调用表,这样您就可以对其进行索引并存储所需的任何元数据,但这会很丑陋并且需要为每个方法创建一个新表。例如,这将允许您将方法转换为可调用表:
local documentMethodMetatable = {}
function documentMethodMetatable.__call(t,...)
  return t.method(...)
end
function documentMethod(method, doc)
  return setmetatable({ method=method, doc=doc}, documentMethodMetatable)
end

然后你可以写这样的东西:
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

关于reflection - Lua - 反射 - 函数参数和文档字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10902079/

相关文章:

java - 如何获取java类中的Luaj函数参数名称?

Java 9 webstart JNLP服务产生IllegalAccess

java - 如何在 Java 中查找特定接口(interface)的所有(子)子接口(interface)?

performance - 在循环内部或外部声明局部更好吗?

string - Lua中将数组中的字符串串联成长字符串

iOS 应用程序未在 Corona 中构建

java - 如何按类将字符串值转换为枚举值?

c# - 获取属性的 JsonPropertyAttribute

c# - 通过反射将方法赋值给委托(delegate)

java - Lua/Java/LuaJ - 处理或中断无限循环和线程