lua-users home
lua-l archive

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


> I've been thinking about Lua string uniqueness and though out of the
> optimization could be made:
> 
> ===============================
> static const char *strconst_rgba = "rgba";
> static const char *strconst_rgba = "rgb";
> static const char *strconst_rgba = "abgr";
> static const char *strconst_rgba = "bgr";
> 
> static int some_c_function (lua_State *L)
> {
>     if (lua_gettop (L) != 1) return 0;
>     const char *arg = lua_tostring (L, 1);
>      /* no 'strcmp ()' here: */
>     if (arg == strconst_rgba) {
>         lua_pushnumber (L, 1);
>         return 1;
>     } else if (arg == strconst_rgb) {
>         lua_pushnumber (L, 1);
>         return 1;
>     } else if (arg == strconst_abgr) {
>         lua_pushnumber (L, 1);
>         return 1;
>     } else if (arg == strconst_bgr) {
>         lua_pushnumber (L, 1);
>         return 1;
>     }
>     return 0;
> }

> {
>     lua_State *L = luaL_newstate ();
>     assert (lua_loadstrconst (L, strconst_rgba)); /* Check for uniqueness */
>     assert (lua_loadstrconst (L, strconst_rgb)); /* Check for uniqueness */
>     assert (lua_loadstrconst (L, strconst_abgr)); /* Check for uniqueness */
>     assert (lua_loadstrconst (L, strconst_bgr)); /* Check for uniqueness */

> The primary idea is to avoid 'strcmp ()'.
> Instead we compare pointers (just the way things work inside Lua VM).

You can do this already, except for the check for uniqueness:

#define lua_loadstrconst(L,s) s=lua_pushstring(L,s)

You also need to ensure that the strings do not get garbage collected,
e.g., save them in the registry or some other global table.