A framework I'm working on may be extended with Lua modules. The Lua sources for each module are compiled with a compiler of ours that's based on the official Lua interpreter and then saved as bytecode. Such modules must meet certain requirements:
-- 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
It would be nice if the requirements could be checked when the Lua sources are compiled into the module. This would make life easier:
- for those writing modules, as they would be told which mistakes they've made; and
- for us, since we could then assume that modules are correct (just as one assumes that installed resources such as icons are correct) and thus wouldn't have to implement any checking at runtime.
Checking that a certain value is of a certain type is not difficult:
// 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!
}
But how would one go about checking that a function takes a certain number of arguments and returns a table with certain fields?
-- 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
Note that I'm asking whether this is possible (and, if so, how) with the C API, unlike this question, which is about doing this from within Lua.