lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]

On 3/31/2020 5:10 AM, Luyu Huang wrote:
I mean Lua reserved words. In fact, my C module accepts strings from Lua
and I need to determine if they are reserved words; they are essentially
TString objects. So if I can get the TString object, I can determine it
directly, Instead of comparing them with a reserved words list, which is
costly. I think it might be better for Lua to provide a function such as
`luaL_isreserved(lua_State *L, int idx)`.

Since a keyword can't be used as the name of a variable, the following will determine if a word (at stack index) is reserved:

    int status = LUA_OK;
    int len = 0;
    const char* str2 = NULL;
    const char* str = lua_tolstring(L, index, &len);
    // test if string matches the pattern "[%a_]%w*"
    // left as exercise for the reader
    if (is_lexical_word(len, str)) {
        lua_pushvalue(L, index);
        lua_pushstring(L, "=true");
        lua_concat(L, 2);
        str2 = lua_tolstring(L, -1, &len);
        status = luaL_loadbuffer(L, str2, len, "=");
        lua_pop(L, 2);
    return status == LUA_ERRSYNTAX;

Attempting to load a string such as "function=true" will cause a syntax error. You still need to check that the string can be a valid name or else the string "black&tan" would be a syntax error even though it's not a keyword.

However, I can't imagine running an entire Lua parser just to check one string is a great use of resources when you could scan a list of strings. Even if you don't want to repeat strcmp so many times, a clever use of strstr will cut down the number of compares at the cost of readability.

-- tom