Search code examples
stringluatypecheckinglua-api

lua_isstring() check for real strings in Lua


int lua_isstring (lua_State *L, int index);

This function returns 1 if the value at the given acceptable index is a string or a number (which is always convertible to a string), and 0 otherwise. (Source)

Is there a (more elegant) way to really proof if the given string really is a string and not a number in Lua? This function makes absolutely no sense to me!

My first idea is to additionally examine the string-length with

 `if(string.len(String) > 1) {/* this must be a string */}`

... but that does not feel so good.


Solution

  • You can replace

    lua_isstring(L, i)
    

    which returns true for either a string or a number by

    lua_type(L, i) == LUA_TSTRING
    

    which yields true only for an actual string.

    Similarly,

    lua_isnumber(L, i)
    

    returns true either for a number or for a string that can be converted to a number; if you want more strict checking, you can replace this with

    lua_type(L, i) == LUA_TNUMBER
    

    (I've written wrapper functions, lua_isstring_strict() and lua_isnumber_strict().)