TIGSource Forums

Developer => Technical => Topic started by: Gregg Williams on October 22, 2013, 06:58:59 PM



Title: Validating arguments passed from Lua to C?
Post by: Gregg Williams on October 22, 2013, 06:58:59 PM
Just wondering if anyone knows any easier ways to validate arguments passed from Lua to C during a function call, other than simply checking for the number of parameters passed in, and then manually verifying each parameters type?

I'm getting a bit tired of doing something like this:
Code:
   int n = lua_gettop(state);
    
    if(n != 3)
    {
        LERROR << "Invalid number of arguments sent to lua_RegisterUnitTemplate";
        return 0;
    }
    
    if(lua_isnumber(state, 1) == false || lua_isstring(state, 2) == false || lua_isnumber(state, 3) == false)
    {
        LERROR << "Invalid argument types passed to lua_RegisterUnitTemplate";
        return 0;
    }


Title: Re: Validating arguments passed from Lua to C?
Post by: epcc on October 22, 2013, 07:20:53 PM
you can use luaL_checknumber(),luaL_checkstring() etc
http://pgl.yoyo.org/luai/i/luaL_checknumber

you can also skip checking the number of arguments, luaL_check... functions will just throw the "bad argument #1 to 'function' (string expected, got no value)".
extra arguments will get ingored.

also an example:

Code:
static int li_DrawText(lua_State* L)
{
    float x  =luaL_checknumber(L,1);
    float y  =luaL_checknumber(L,2);
    const char* str=luaL_checkstring(L,3);

    DrawString(str,x,y);
    return 0;
}


Title: Re: Validating arguments passed from Lua to C?
Post by: Gregg Williams on October 22, 2013, 07:52:04 PM
Oh hey thanks! Thats quite cool.

I was just starting to write a variadic function to accept parameter types and do a big switch, but this seems great.