这个部分展现全部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 )...
水平有限,若有错误,给出指正。