這個部分展現全部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 ) ...
不少編輯器都有插入空格代替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;
void f( int i ) { // function code here } f( 2 ); // function call
void f ( int i ) { // function code here } f ( 2 ); // function call
4.變量的定義:使用GNU風格,加上下劃線和小寫字母。函數
int simple; double another_identifier; char yes_this_is_OK_although_quite_stupid;
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();
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();
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
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 )...
水平有限,若有錯誤,給出指正。