跳轉到內容

Ring/教程/變數

來自華夏公益教科書,自由的教學讀本

要建立一個新變數,你只需要確定變數名和值。值將決定變數型別,你可以使用相同的變數名更改值以在型別之間切換。

語法

	
	<Variable Name> = <Value>

.. tip:

運算子 '=' 在這裡用作賦值運算子,相同的運算子可以在條件中使用,但用於測試表達式的相等性。

.. note:

變數將包含實際值(而不是引用)。這意味著一旦你改變變數值,舊值將從記憶體中刪除(即使變數包含列表或物件)。


動態型別

[編輯 | 編輯原始碼]

Ring 是一種動態程式語言,它使用`動態型別 <http://en.wikipedia.org/wiki/Type_system>`_。

	x = "Hello"		# x is a string
	see x + nl
	x = 5			# x is a number (int)
	see x + nl
	x = 1.2 		# x is a number (double)
	see x + nl
	x = [1,2,3,4]		# x is a list
	see x 			# print list items
	x = date()		# x is a string contains date
	see x + nl
	x = time()		# x is a string contains time
	see x + nl
	x = true		# x is a number (logical value = 1)
	see x + nl
	x = false		# x is a number (logical value = 0)
	see x + nl

深複製

[編輯 | 編輯原始碼]

我們可以使用賦值運算子 '=' 來複制變量。我們可以這樣做來複制字串和數字等值。此外,我們可以複製完整的列表和物件。賦值運算子將為我們進行完整的複製。此操作稱為`深複製 <http://en.wikipedia.org/wiki/Object_copy#Deep_copy>`_


	list = [1,2,3,"four","five"]
	list2 = list
	list = []
	See list	# print the first list - no items to print
	See "********" + nl
	See list2	# print the second list - contains 5 items

弱型別

[編輯 | 編輯原始碼]

Ring 是一種`弱型別語言 <http://en.wikipedia.org/wiki/Strong_and_weak_typing>`_,這意味著該語言可以在有意義的情況下自動在資料型別之間轉換(如字串和數字)。

規則

	<NUMBER> + <STRING> --> <NUMBER>
	<STRING> + <NUMBER> --> <STRING>

.. note:

相同的運算子 '+' 可以用作算術運算子或用於字串連線。

示例

	x = 10			# x is a number
	y = "20"		# y is a string
	sum = x + y		# sum is a number (y will be converted to a number)
	Msg = "Sum = " + sum 	# Msg is a string (sum will be converted to a string)
	see Msg + nl


華夏公益教科書