Cocos2dx+lua中Color参数的坑

cocos2x的lua中有如下几种颜色定义

--Color3B
function cc.c3b( _r,_g,_b )
return { r = _r, g = _g, b = _b }
end

--Color4B
function cc.c4b( _r,_g,_b,_a )
return { r = _r, g = _g, b = _b, a = _a }
end

--Color4F
function cc.c4f( _r,_g,_b,_a )
return { r = _r, g = _g, b = _b, a = _a }
end

今天使用Cocos2dx的Label碰到一个问题,我感觉挺容易被忽略的

virtual void enableShadow(const Color4B& shadowColor = Color4B::BLACK,const Size &offset = Size(2,-2), int blurRadius = 0);

使用Label的enableShadow函数定义的颜色要求是Color4B,如果不小心使用了Color3B就根本没有效果

我看了下从lua表转化到C++中Color4B的代码,结果是为空时就赋值为0,所以使用Color3B传进来,alpha值为nil,它直接赋值为0了

全透明了当然也就看不到了。。。

bool luaval_to_color4b(lua_State* L,int lo,Color4B* outValue)
{
    if (NULL == L || NULL == outValue)
        return false;
    
    bool ok = true;

    tolua_Error tolua_err;
    if (!tolua_istable(L, lo, 0, &tolua_err) )
    {
#if COCOS2D_DEBUG >=1
        luaval_to_native_err(L,"#ferror:",&tolua_err);
#endif
        ok = false;
    }
    
    if(ok)
    {
        lua_pushstring(L, "r");
        lua_gettable(L,lo);
        outValue->r = lua_isnil(L,-1) ? 0 : lua_tonumber(L,-1);
        lua_pop(L,1);
        
        lua_pushstring(L, "g");
        lua_gettable(L,lo);
        outValue->g = lua_isnil(L,-1) ? 0 : lua_tonumber(L,-1);
        lua_pop(L,1);
        
        lua_pushstring(L, "b");
        lua_gettable(L,lo);
        outValue->b = lua_isnil(L,-1) ? 0 : lua_tonumber(L,-1);
        lua_pop(L,1);
        
        lua_pushstring(L, "a");
        lua_gettable(L,lo);
        outValue->a = lua_isnil(L,-1) ? 0 : lua_tonumber(L,-1);
        lua_pop(L,1);
    }
    
    return ok;
}

还有如果需要传入Color4F的地方如果传入了Color3B或者Color4B也会不正常

因为Color4F要求rgba范围都是0~1

void drawDot(const Vec2 &pos, float radius, const Color4F &color);

lua本来就是弱类型的这样很容易出错!!

只能自己多加注意了

原文地址:https://www.cnblogs.com/luweimy/p/4113063.html