【发布时间】:2017-01-12 02:51:48
【问题描述】:
我正在开发的框架可以使用 Lua 模块进行扩展。每个模块的 Lua 源代码都使用我们的编译器编译,该编译器基于官方 Lua 解释器,然后保存为字节码。此类模块必须满足某些要求:
-- Must be a non-empty string consisting only of characters in the range a-z
name = "foo"
-- Must not only be a number, but also an integer greater than zero
version = 1
如果 Lua 源代码编译到模块中时可以检查需求,那就太好了。这将使生活更轻松:
- 对于那些编写模块的人,因为他们会被告知他们犯了哪些错误;和
- 对我们来说,因为我们可以假设模块是正确的(就像假设已安装的资源(如图标)是正确的一样),因此不必在运行时实施任何检查。
检查某个值是否属于某个类型并不难:
// lua_getglobal returns the type of the value
int r = lua_getglobal(lua_state, "name");
if ( r == LUA_TSTRING )
{
// well done, dear module writer (well, must still check if the string contains
// only valid characters)
}
else if ( r == LUA_TNIL )
{
// error: `name' not defined
}
else
{
// hey you, `name' should be a string!
}
但是如何检查一个函数是否接受一定数量的参数并返回一个包含特定字段的表呢?
-- must be defined with two parameters
function valid_function( arg1 , arg2 )
-- must return a table
return {
a = 17, -- with field `a', a number
b = "a" -- with field `b', a string
}
end
请注意,我问的是 C API 是否可能(如果可以,如何),不像 this question,它是在 Lua 中执行此操作。
【问题讨论】: