[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: C string pointers to Lua
- From: Peter Cawley <lua@...>
- Date: Tue, 12 Oct 2010 11:47:10 +0100
On Tue, Oct 12, 2010 at 11:33 AM, Robert Raschke
<rtrlists@googlemail.com> wrote:
>
> On Tue, Oct 12, 2010 at 11:09 AM, Rebel Neurofog <rebelneurofog@gmail.com>
> wrote:
>>
>> 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;
>> }
>>
>> int main ()
>> {
>> 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 */
>>
>> /* bind 'some_c_function ()' here */
>> /* execute some code */
>>
>> return 0;
>> }
>> =======================
>>
>> The primary idea is to avoid 'strcmp ()'.
>> Instead we compare pointers (just the way things work inside Lua VM).
>>
>> What do you think? Is it too mad?
>>
>> P. S. luaL_checkoption () uses strcmp ()
>>
>
> I'd assume that strcmp() is already pretty heavily optimised. Compilers will
> inline it when at least one of the two args is a literal or a local const
> (at least that's what was happening 15 years ago, been a while since I
> worked on a compiler). And I'd be slightly shocked if it didn't already do
> the pointer comparison before jumping into byte comparisons.
>
> Robby
I would lean toward an approach like the following:
static int some_c_function(lua_State* L)
{
if(lua_gettop(L) != 0) return 0;
lua_rawget(L, lua_upvalueindex(1));
switch(lua_tointeger(L, 1))
{
case 1: // RGBA
case 2: // RGB
case 3: // ABGR
case 4: // BGR
lua_pushnumber(L, 1);
return 1;
default:
return 0;
}
}
int main()
{
// etc.
lua_newtable(L);
#define keyval(k, v) \
lua_pushliteral(L, k); \
lua_pushinteger(L, v); \
lua_rawset(L, -3)
keyval("rgba", 1);
keyval("rgb" , 2);
keyval("abgr", 3);
keyval( "bgr", 4);
#undef keyval
lua_pushcclosure(L, some_c_function, 1);
// etc.
}