我正在使用的框架可以通过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
你不能这样做。每个Lua函数可以接受任意数量的参数并返回任意数量的任何类型的值。
我认为您最好的办法是在某处(在注释中或运行时出现的内容中)编写显式类型注释,然后进行检查。还有Typed Lua,它是带有静态类型系统的实验性Lua方言。
例如,函数如何接收任意数量的参数,如果函数接收的参数少于其具有参数的参数,则多余的参数将分配给nil
。如果传递的参数比函数作为参数传递的参数多,则多余的参数将被丢弃。
function foo(x, y)
print(x,y)
end
foo() -- prints nil, nil
foo(1) -- prints 1, nil
foo(1,2) -- prints 1, 2
foo(1,2,3) -- prints 1, 2
缺少参数benil
通常也用于实现带有可选参数的函数,这意味着幼稚的尝试检查参数数量将与以下通用Lua习惯冲突:
function hello(name)
name = "mysterious stranger"
print("Hello, "..name.."!")
end
返回参数也很灵活,就像输入参数一样:
function bar()
return 1, 2
end
local x = bar() -- second return value gets discarded
local x, y = bar()
local x, y, z = bar() - z gets assigned to `nil`
许多Lua函数还根据条件返回不同数量的参数。例如,io.open
如果可以打开文件,则返回一个值(文件句柄),如果不能打开,则返回两个值(nil后跟错误消息)。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句