Skip to content

Instantly share code, notes, and snippets.

@balaam
balaam / reverseTable.lua
Created July 16, 2012 10:59
Reverse an ipairs table in Lua (not clever O(n) could be O(n/2) with swapping)
--
-- Reverses an ipairs table
--
--local r = ReverseTable({'a', 'b', 'c'})
--for k, v in ipairs(r) do
-- print(k, v)
--end
--
--
function ReverseTable(t)
@balaam
balaam / combinations.lua
Created August 14, 2012 20:55
Get all combinations of items in a table
function AllCombinations(list, stop)
stop = stop or #list
if stop == 0 then
return list
end
local collect = {}
for k, v in pairs(list) do
@balaam
balaam / subcombinations.lua
Created August 14, 2012 21:01
Get all combinations and all sub combinations in a table (I'm sure there's a term for this!)
function AllCombinations(list, stop)
stop = stop or #list
if stop == 0 then
return list
end
local collect = {}
for k, v in pairs(list) do
@balaam
balaam / TypeHolder.cpp
Created August 21, 2012 09:51
Storing type information about an object with out templating the outer object or having inhertance on the parent object. Exploring some code that uses a similar method for C++ reflect system
#include "cstdio"
// No type information
class ClassMeta
{
class Holder
{
public:
virtual void* GetPtr() const { return NULL; }
protected:
@balaam
balaam / WrapZeroOne.lua
Created August 22, 2012 14:56
Wrap a number in the range 0-1. e.g. 1.3 becomes 0.3
function WrapZeroOne(value)
value = value - math.floor(value)
if value < 0 then
x = x + 1
end
return value
end
@balaam
balaam / wrap
Created December 16, 2012 13:01
Cyclic array access Lua vs C-languages
--
-- In C style languages you can cyclically access elements of an array using the modulus operator
--
-- Lua-style psuedo code:
--
-- array = {'a', 'b', 'c', 'd'};
-- i = 0;
-- while true do
-- print(array[i % array.count()]);
-- i++;
Stats = {}
Stats.__index = Stats
function Stats:Create(stats)
local this =
{
mBase = {},
mModifiers = {}
}
-- Shallow copy
public class OddmentTable<T>
{
// Allows comparison of generic types.
//See: http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=193203&SiteID=1
private static readonly IEqualityComparer<T> comparer =
EqualityComparer<T>.Default;
protected List<Entry> entries = new List<Entry>();
protected int oddment = 0;
protected Random random;
@balaam
balaam / JRPG - Levels
Created February 5, 2014 11:59
Example code for a levelling up system in a JRPG. As explained on my blog http://www.godpatterns.com and upcoming book: www.howtomakeanrpg.com
function nextLevel(level)
local exponent = 1.5
local baseXP = 1000
return math.floor(baseXP * (level ^ exponent))
end
Stats = {}
Stats.__index = Stats
function Stats:Create(stats)
local this =
public static float LerpF( float value, float in0, float in1, float out0, float out1 )
{
float normed = (value - in0) / (in1 - in0);
float result = out0 + (normed * (out1 - out0));
return result;
}