ID:195114
 
//Title: Direction Name
//Credit to: Jtgibson
//Contributed by: Jtgibson


//This simple proc is just used to output directions
// as text rather than as numerals.
//It uses bitwise logic to construct a string.

//This isn't faster than comparing the directions to a list, but it
// shows you how you can use bitwise stuff on directions.


proc/dir2text(direction)
var/string = ""

if(direction & NORTH)
string += "NORTH"
if(direction & SOUTH)
string += "SOUTH"
if(direction & EAST)
string += "EAST"
if(direction & WEST)
string += "WEST"

return(string)


///*
//Testing code/sample implementation:

mob/verb/test_dir2text()
var/list/directions = list(NORTH, NORTHEAST, EAST,
SOUTHEAST, SOUTH, SOUTHWEST, WEST, NORTHWEST)

usr << "Directions in raw numerical form:"
//Show all directions but the last in the list
for(var/i = 1, i < directions.len, i++)
usr << "[directions[i]], \..."
//Show the last one in the list
usr << directions[directions.len]

usr << "Directions in dir2text form:"
for(var/i = 1, i < directions.len, i++)
usr << "[dir2text(directions[i])], \..."
usr << dir2text(directions[directions.len])
//*/
Beautiful! I love this! =)
Jtgibson wrote:
//This isn't faster than comparing the directions to a list, but it
> // shows you how you can use bitwise stuff on directions.
>
>
> proc/dir2text(direction)
> var/string = ""
>
> if(direction & NORTH)
> string += "NORTH"
> if(direction & SOUTH)
> string += "SOUTH"
> if(direction & EAST)
> string += "EAST"
> if(direction & WEST)
> string += "WEST"


Well, it certainly couldn't hurt the speed if you cleaned up the if() chain a bit; if direction & NORTH == TRUE, then direction & SOUTH == FALSE --- This is what else if() is for! ;)

(Same goes for EAST/WEST)

Hiead
In response to Hiead
Why bother? It'll have to do one less bitwise comparison per axis. We're talking on the order of a single CPU-integral operation each. Even on an innermost loop this wouldn't do anything significant.

Besides, there's always the possibility that someone's giving it a non-standard direction in order to use it as a mask... NORTHSOUTHEASTWEST for instance. =)