Snippets

Context aware Lua Macros

February 18th, 2010 0 Comments

Will automatically detect locals as well as global variables.

Usage: Macro “text ${Lua Code} more text”

local _mtg = getmetatable(_G) or {}
function _mtg.__index(self, k)
	return rawget(self,k.."___macro")
end
setmetatable(_G,_mtg)

function string.escape(text)
	local str = ""
	for i=1, #text do
		local chr = text:sub(i,i)
		local escape = ""
		if isIn(chr, {"(", ")"}) then escape = "%" end
		str = str .. escape..chr
	end
	return str
end

function isIn(obj, table)
	for _,v in ipairs(table) do
		if obj == v then return true end
	end
end

function get_locals(func)
     local n = 1
     local locals = {}
     func = (type(func) == "number") and func + 1 or func
     while true do
          local lname, lvalue = debug.getlocal(func, n)
          if lname == nil then break end
          if lvalue == nil then lvalue = mynil end
          locals[lname] = lvalue
          n = n + 1
     end
     return locals
end

Macro = setmetatable({}, {__call=function(self, ...) return self:init(...) end})
function Macro:init(...)
	--We want to retain processing capability even after declaration
	local args = {...}
	local __string = ""
	for _,obj in ipairs(args) do
		__string = __string .. tostring(obj)
	end
	local members = {
		__string = __string,
		type="Macro"
	}
	local methods = {
		__tostring__ = function(self, n)
			--Actual Processing Logic goes here
			local str = self.__string
			local match = "${.-[^\\]}"
			--Check if str has ${statement}
			local indices = {str:find(match)}
			while #indices > 0 do
				local sub = str:sub(indices[1]+2, indices[2]-1)
				local repl = str:sub(unpack(indices))
				local final = ""
				local locals = get_locals(3+n)
				for k,_ in pairs(locals) do
					rawset(_G,k.."___macro",_)
				end
				--Evaluate
				local _fn, e = loadstring(sub)
				if not _fn then
					_fn, e = loadstring("return "..sub)
				end
				if not _fn then
					final = " "..e.." "
				else
					final = tostring(_fn() or " ")
				end
				for k,_ in pairs(locals) do
					rawset(_G,k.."___macro",nil)
				end
				str = str:gsub(repl:escape(), final)
				indices = {str:find(match)}
			end
			return str
		end,
		__tostring = function(self)
			return getmetatable(self).__tostring__(self, 2)
		end,
		__call = function(self)
			return getmetatable(self).__tostring__(self, 0)
		end
	}
	return setmetatable(members, methods)
end

test = Macro "Hello ${jack} ${'Bauer'}"

function test1()
	local jack = "Jack"
	print(test)
end

test1()

function test2()
	local jack = "No One"
	print(test)
end

test2()

function test3()
	local test = Macro "Hello ${world}"
	local world = "World"
	print(test())
end

test3()

function test4()
	local test = Macro "Hello ${print('asdf'); return 'World'}"
	local world = "World"
	print(test)
end

test4()

Best Hello World App Ever :D

February 1st, 2010 0 Comments

Written in Python :D

See http://failboat.me/2009/cute-functions-creating-pseudo-operators-in-python/ for more details.

#Hello World

class Operator(object):
    def __init__(self, func, count=2):
        self._func_ = func
        self._args_ = []
        self._count_ = count
    def __ror__(self, first_arg):
        self._args_.append(first_arg)
        return self
    def __or__(self, arg):
        self._args_.append(arg)
        if len(self._args_) >= self._count_:
            return self(*self._args_)
        else:
            raise RuntimeError("Incorrect number of parameters")
    def __call__(self, *args, **kwargs):
        self._args_ = []
        return self._func_(*args, **kwargs)

def alpha(letter):
    @Operator
    def _alpha(a,b):
        return a+letter+b
    return _alpha

for c in range(65, 122):
    globals()[chr(c)] = alpha(chr(c))

print "H"|e|"l"|l|"o","W"|o|"r"|l|"d"

Gettings the most out of your bits

November 1st, 2009 0 Comments

The following will produce the bit representation of an ord(byte) in python

def bit(chr, i=0, str=''):
    if i > 7: return str
    coef = (2**(8-i-1))
    if chr >= coef: return bit(chr-coef, i+1, str+'1')
    return bit(chr, i+1, str+'0')

Example

print bit(ord(“a”))
01100001

Primitive Collision Detection – Circular objects

October 31st, 2009 0 Comments

Consider the following –

If you are designing a game, and have the players shaped as circles, how would you detect bullet collisions with the players?

Well, the problem with bullet collision detection is that you can’t just use traditional collision detection algorithms with static objects. The bullet itself can be seen as a continuous object, thus we need to devise a new way to solve the problem

[Python] Get Function Args

October 28th, 2009 0 Comments

getargs = lambda func: (func.func_code.co_varnames[:func.func_code.co_argcount])

Example Session


#Example Session

getargs = lambda func: (func.func_code.co_varnames[:func.func_code.co_argcount])
def addition(x,y):
    return x+y
print getargs(addition)
#('x', 'y')

Yep, it’s really that simple. No weird exec functions needed, no intrusive introspection via the disassembler.

Cute Functions – Creating pseudo-operators in Python

October 26th, 2009 1 Comments

I ran across something today that I found to be extremely interesting. Basically, the authors of Should_DSL, http://pypi.python.org/pypi/should_dsl/1.2.1, have attempted and succeeded in creating pseudo-operators based on operator-functions within an object.

Let me elaborate.

The goal of Should-DSL is to write should expectations in Python as clear and readable as possible, using “almost” natural language (with limitations from Python language).

And to be honest, they’ve got it all right.

Python limits function calls to callable objects through the () notation. However, custom functors can also have their own __call__ method invoked when an operator or a reverse operator is used on them. Take for example the following code

class WeirdFunc(object):
    def __init__(self, func):
        self.func = func
    def __radd__(self, arg):
        return self(arg)
    def __call__(self, *args, **kwargs):
        return self.func(*args, **kwargs)

@WeirdFunc
def one(other):
    return other+1

print "'3+one' will evaluate to %s"%(3+one)

Will yield ‘3+one’ will evaluate to 4

So taking this to a whole new level, the folks at Should_DSL have created their assertion operators to be as semantic as possible. The syntax taking form to look something like

from should_dsl import *
import unittest

class UsingShouldExample(unittest.TestCase):
...     def test_showing_should_not_be_works(self):
...         'hello world!' |should_not_be| 'Hello World!'
...
...     def test_showing_should_have_fails(self):
...         [1, 2, 3] |should_have| 5
...
...     def test_showing_should_have_works(self):
...         'hello world!' |should_have| 'world'
...
...     def test_showing_should_not_have_fails(self):
...         {'one': 1, 'two': 2} |should_not_have| 'two'
...
...     def test_showing_should_not_have_works(self):
...         ["that's", 'all', 'folks'] |should_not_have| 'that'

from cStringIO import StringIO
runner = unittest.TextTestRunner(stream=StringIO())
suite = unittest.TestLoader().loadTestsFromTestCase(UsingShouldExample)
runner.run(suite)

Notice that in place of self.assert*, the tests instead uses x |should_[not]_be| y, which while verbose, is intuitive when placed in the context of running tests (which are by convention much more tolerant of verbosity).

So how do they do it? The key here is that the ‘|’ operator can be functionalized as the __or__ and __xor__ method of any given object. Thus we can cache the values passed to __or__ (the second argument) and __xor__ (the first argument) and then pass that back to the __call__ method.

We can easily prototype a decorator class for this pseudo-operator object

class Operator(object):
    def __init__(self, func, count=2):
        self._func_ = func
        self._args_ = []
        self._count_ = count
    def __ror__(self, first_arg):
        self._args_.append(first_arg)
        return self
    def __or__(self, arg):
        self._args_.append(arg)
        if len(self._args_) >= self._count_:
            return self(*self._args_)
        else:
            raise RuntimeError("Incorrect number of parameters")
    def __call__(self, *args, **kwargs):
        self._args_ = []
        return self._func_(*args, **kwargs)

Here the variables are cached in the obj._args_ list, which is unpacked as the parameters of the __call__ method in the second ‘|’. An example usage would be as follows:

@Operator # Turns the plus function into the |plus| operator #
def plus(first, second):
    return first+second

print 1 |plus| 2
# Will return 3

Happy Coding

[Lua] MapParser (High Level API)

October 25th, 2009 0 Comments

This is a Map parser library for CS2D's lua engine. Benchmarked to process 6,000 tiles per second. (A 2,000% improvement over the older parser). This also demonstrates that it is possible to have object-orientation within a lua script and to work with CTypes.

Code/Download:
http://pastebin.com/f33323412
MapParser
Future implementations will also add caching.

API:

Map:new(mapfile)
Creates a new instance of the Map object
IE: map = Map:new("maps/de_dust.map")

Map:invert(table)
Inverts the x and the y of a given table (must be in matrix form)
IE: dumpable = map:invert(map.tiles)

Map:dumpMeta()
Creates a dump of all of the meta-information stored in a map
IE: map:dumpMeta()
Output:
[Table:(Anonymous)]
code = 8100x79$123225%4595857
loadtime = 1.77
header = Unreal Software's Counter-Strike 2D Map File (max)
...

Map:mapogram()
Prints out a graphical display of the collision gradients
IE: map:mapogram() -- See above for output

Map.tiles[x][y]
A table of tile data, accessed through map.tiles[x][y]
IE: tile_3_4 = map.tiles[3][4] -- stores the tile at 3,4 into tile_3_4

Map.modes[x][y]
A table of the tile modes, accessed through map.modes[x][y], note here that modes will tell you whether a tile is a wall or not
IE: mode_20_32 = map.modes[20][32]

Map.entities[id]
A table of the individual entities, accessed through map.entities[id]
IE: entity_3 = map.entities[3]

Map.collisions[x][y]
A table of walls and obstacles. 0 if not an obstacle, 1 through 4 if it is.
IE: map.collisions[7][8]

Map.gradient, Map.antigradient - use ipairs
Table of collisions and non-collisions that can be iterated via ipairs(), stored in {x, y, mode} format
IE: for _i, coordinate in ipairs(map.gradient) do blahblah() end

Example implementation of http://unrealsoftware.de/lab_cat.php?ca ... =#entry499

dofile(core_dir.."map.lua")
current_map = Map:new("maps/"..map("name")..".map")

function tile(x,y,prop)
     local args = {}

     args.entity = current_map.entities [x] [y]
     args.tile = current_map.tiles[x] [y]
     args.mode= current_map.modes[x] [y]
     args.collision= current_map.collisions[x] [y]

     if args.collision == 0 then args.collision = false end

     if prop then
               if args[prop] then return args[prop] end
     end

     return args
end

if tile(12,30,"collision") then
     --Custom Code Here.
end

Notices
Requires the struct.lua, string.lua, and table.lua libraries. (Look inside amx2d/core)

Python – Abstract Function class

August 2nd, 2009 0 Comments

Python is great. It’s dynamic, it’s flexible, and best of all, for almost all major datatypes, there’s an associated abstract class from which you can over-ride and build your own object out of.

Of course, Python doesn’t treat functions in this same way. But as developers we cope and we move on when we have to.

Until recently I’ve been blissfully oblivious of this fact, of course I’ve never had the need to overload the default functionality of a function and thus have never had needs of an abstract class for functions as well. As far as I’m concerned, using the def operator is much more simplistic than having to toil to create a brand new class and in doing so cheating python out of its gracefulness.

But a few days ago I had to write a program in which native python functions are given and the program needs to find out whether the functions’ opcodes matches and return true if it does. Naturally I assumed that the == operator for functions covers this aspect. I was shocked to find out that it doesn’t. Now I’m stuck with one of two ways out. I could write a messy block of code to manually check for the func_code.co_code, or I could write my own abstract class for function types and then just use the == operator to keep everything elegant.

Well, I must have been bored because rather then going along with writing an intermediate function to do the checking, I actually wrote a whole base-class to replicate a function’s, well, functionalities.

The class started off as it would for any other class, I knew that I wanted an object that’s callable, and when attributes are being requested would return instead those from the function that it’s derived from. I want to keep things as simple as possible so the only instance member of this class would be the actual function that it’s derived from.

The skeleton code for thus far goes like