eLua 编程风格


这个部分展现全部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.编辑器

固然,关于“{”和“}”的缩进也要注意。ide

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.在代码里使用常量:永远不要像下面这样写代码:ui

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 integerthis

  • u8: unsigned 8-bit integerlua

  • s16: signed 16-bit integerspa

  • u16: unsigned 16-bit integercode

  • s32: signed 32-bit integer

  • u32: unsigned 32-bit integer

  • s64: signed 64-bit integer

  • u64: unsigned 64-bit integer

采用特定数据类型的好处是让你在不一样平台上能有高度的可移植性。可是不要过分使用它,好比,通常for循环中都是使用int索引,可是若是你想定义超时时间,它有32位,明确的用u32声明代替unsigned int.

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 )...

固然若是你使用其它第三方平台语言(来自支持的库或者包),那么也按照上面的规则来吧,可是这不是强制性的。将注意力放在功能实现上而且按照你认为合适的方法书写。


水平有限,若有错误,给出指正。

相关文章
相关标签/搜索