Welcome, Guest. Please login or register.
Did you miss your activation email?

Login with username, password and session length

 
Advanced search

1352835 Posts in 62417 Topics- by 54158 Members - Latest Member: tonym

December 17, 2018, 05:27:21 AM

Need hosting? Check out Digital Ocean
(more details in this thread)
TIGSource ForumsDeveloperTechnical (Moderator: ThemsAllTook)Validating arguments passed from Lua to C?
Pages: [1]
Print
Author Topic: Validating arguments passed from Lua to C?  (Read 1018 times)
Gregg Williams
Level 10
*****


Retromite code daemon


View Profile WWW
« 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;
    }
Logged

epcc
Level 1
*


View Profile
« Reply #1 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;
}
Logged

Gregg Williams
Level 10
*****


Retromite code daemon


View Profile WWW
« Reply #2 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.

Logged

Pages: [1]
Print
Jump to:  

Theme orange-lt created by panic