Updated tutorial_gdscript_efficiently (markdown)

reduz 2014-09-20 07:59:13 -07:00
parent 42a2a85244
commit 071c544457

@ -163,6 +163,80 @@ use_array(array) # passed as reference
#freed when no longer in use
```
In dynamically typed languages, arrays can also double as other datatypes, such as lists:
```python
var array = []
array.append(4)
array.append(5)
array.pop_front()
```
or unordered sets:
```python
var a = 20
if a in [10,20,30]:
print("We have a Winner!")
```
### Dictionaries
Dictionaries are always a very powerful in dynamically typed languages. Most programmers that come from statically typed languages (such as C++ or C#) ignore their existence and make their life unnecessarily more difficult. This datatype is generally not present in such languages (or only on limited form).
Dictionaries can map any value to any other value with complete disregard for the datatype used as either key or value. Contrary to popular belief, they are very efficient because they can be implemented with hash tables. They are, in fact, so efficient that languages such as Lua will go as far as implementing arrays as dictionaries.
Example of Dictionary:
```python
var d = { "name":"john", "age":22 } # simple syntax
print("Name: ", d["name"], " Age: ", d["age"] )
```
Dictionaries are also dynamic, keys can be added or removed at any point at little cost:
```python
d["mother"]="Rebecca" # addition
d["age"]=11 # modification
d.erase("name") #removal
```
Two-dimensional arrays can often be implemented easier with dictionaries. Here's a simple battleship game example:
```python
#battleship game
const SHIP=0
const SHIP_HIT=1
const WATER_HIT=2
var board={}
func initialize():
board[Vector(1,1)]=SHIP
board[Vector(1,2)]=SHIP
board[Vector(1,3)]=SHIP
func missile(pos):
if pos in board: #something at that pos
if board[pos]==SHIP: #there was a ship! hit it
board[pos]=SHIP_HIT
else:
print("already hit here!") # hey dude you already hit here
else: #nothing, mark as water
board[pos]=WATER_HIT
func game():
initialize()
missile( Vector2(1,1) )
missile( Vector2(5,8) )
missile( Vector2(2,3) )
```