这个部分展示所有elua开发者都应该注意的elua编程风格。规则如下:
1.空格无处不在。例子如下(空格规则是为了增加程序的可读性)。
i = 3 (not i=3)
a = ( a + 5 ) / 3
for( i = 0; i < 10; i ++ ) ...
if( ( i == 5 ) && ( a == 10 ) ) ...
unsigned i = ( unsigned )p;
void func( int arg1, const char* arg2 ) ...
2. 缩进:缩进距离为两个空格。再一次说明,是SPACE,而不是TAB。这非常重要(当然也容易记住),有许多关于TAB键毁了代码可读性的例子。
很多编辑器都有插入空格代替TAB的选项,选上它。并且设置TAB宽度为2.
当然,关于“{”和“}”的缩进也要注意。
if( i == 2 )
{
// some code here
}
else
{
// some other code here
}
或者
void f( int i )
{
// function code
}
不要在只有一条语句的时候用“{”和“}”将语句围住。就像下面这样:
if( i == 2 )
return;
来代替下面的书写:
if( i == 2 )
{
return;
}
当然,要遵循一条语句一行的书写规则,也就是不要像下面这样书写:
if( i == 2 ) return;
而是这样写:
if( i == 2 )
return;
还要注意的是eLua代码在函数名和参数之间没有空格。定义函数或调用函数时都是这样。就像下面这样。
void f( int i )
{
// function code here
}
f( 2 ); // function call
而不是下面这样:
void f ( int i )
{
// function code here
}
f ( 2 ); // function call
3. 行终止符:这在使用UNIX行终止符风格(LF)的系统中很重要,而不是DOS风格(CR\LF)或者MAC风格终止符(CR)。
4.变量的定义:使用GNU风格,加上下划线和小写字母。
int simple;
double another_identifier;
char yes_this_is_OK_although_quite_stupid;
5. 不要使用匈牙利命名法(比如iNumber,sString,fFloat)。当然它有它适合的地方,但不适合eLua。
6.在代码里使用常量:永远不要像下面这样写代码:
if( key == 10 )
sys_ok();
else if( key == 5 )
phone_dial( "911" );
else if( key == 666 )
{
while( user_is_evil() )
exorcize_user();
}
else if( key == 0 )
sys_retry();
else
sys_error();
与上面不同的是,使用定义一些有意义名字的常量来代替(使用enum或#define),写出来就是这个样子:
if( key == KEY_CODE_OK )
sys_ok();
else if( key == KEY_CODE_FATAL_ERROR )
phone_dial( "911" );
else if( key == KEY_CODE_COMPLETELY_EVIL )
{
while( user_is_evil() )
exorcize_user();
}
else if( key == KEY_CODE_NONE )
sys_retry();
else
sys_error();
7. 尽可能使用特定的数据类型:在这里特定数据类型代表在所有平台上都适用的数据类型。它们在每个平台中都有定义,且含义如下:
-
s8: signed 8-bit integer
-
u8: unsigned 8-bit integer
-
s16: signed 16-bit integer
-
u16: unsigned 16-bit integer
-
s32: signed 32-bit integer
-
u32: unsigned 32-bit integer
-
s64: signed 64-bit integer
-
u64: unsigned 64-bit integer
8.大小端格式:记住你的eLua可能运行在大端或者小端的处理器架构上。通过代码来表现这种情况。
9.注释:我们通常喜爱C++风格的注释(//),但是使用C风格注释也是可以的(/**/)。尽量的按你需要的书写,不需要写太多细节,但是也不要省略掉重点。特别的,不要像下面这样书写:
// This function returns the sum of two numbers
// Input: n1 - first number
// Input: n2 - the second number
// Output: the sum of n1 and n2
int sum( int n1, int n2 )
{
return n1 + n2;
}
当很多事情可以从程序内容中显而易见的看出来时,再添加注释就是毫无意义的并且还降低了可读性。
10.虚拟命名空间:因为在C中不存在命名空间。所以试着在变量,函数等前面加上前缀来模仿以表现出这个文件的独特性。但这不是一个确定的规则要求,比如一个叫做"uart.c"的文件内容可能如下:
int uart_tx_count, uart_rx_count;
int uart_receive( unsigned limit )...
unsigned uart_send( const char *buf, unsigned size )...
当然如果你使用其它第三方平台语言(来自支持的库或者包),那么也按照上面的规则来吧,但是这不是强制性的。将注意力放在功能实现上并且按照你认为合适的方法书写。
水平有限,如有错误,给出指正。