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

固然若是你使用其它第三方平臺語言(來自支持的庫或者包),那麼也按照上面的規則來吧,可是這不是強制性的。將注意力放在功能實現上而且按照你認爲合適的方法書寫。


水平有限,若有錯誤,給出指正。

相關文章
相關標籤/搜索