Category Archives: DLed
Asynchronously access an object’s property repeatedly in C#
A question on Stackoverflow got me thinking of a beautiful way of reporting a value of an object in C# repeatedly, something like polling a sensor. Typically, polling is pull-based, but having been reading Intro to Rx for the second time lately, and being convinced of its push-base structural and syntactic eunoia, I’ve created a solution based on Rx listed below.
using System; using System.Reactive.Concurrency; using System.Reactive.Linq; namespace rxtest { class FrequencyMeter { Random rand = new Random(); public int Hz { get { return 60+rand.Next(3); } } } class Program { static void Main(string[] args) { var obs = Observable.Generate<FrequencyMeter, int>( new FrequencyMeter(), //state x => !Console.KeyAvailable, // while no key is pressed x => x, // no change in the state x => x.Hz, // how to get the value x => TimeSpan.FromMilliseconds(250), //how often Scheduler.Default) .DistinctUntilChanged() //show only when changed ; using (var _ = obs.Subscribe(x => Console.WriteLine(x))) { var ticks = Observable.Interval(TimeSpan.FromSeconds(0.5)) .Subscribe(x=>Console.WriteLine("tick")); //an example only Console.WriteLine("Interrupt with a keypress"); Console.ReadKey(); } } } }
producing an output similar to that:
Interrupt with a keypress 62 60 62 tick 61 60 tick 62 61 tick 60 62 61 tick 62
Now, with Rx available in C++ that would be interesting what will be left of the eunoia.
a generic c++ lua stack crawler
Sometimes one needs to walk the Lua stack on the C++ side, for example, if passing tables to C++ via the new extended LuaBridge functionality.
For that I’ve started luastackcrawler (see on github). The small test shows that it works at least in principle.
A possible use case – configuration. If the layout of a stack entry, such as a table is known, one can write own wrappers around those to easily access the values. Right now one can iterate through stack and Lua table values, which can be of several types, represented by a boost::variant
.
Example, lua:
assert( ArraySize { 1, 2, 5, bla='7' } == 3 )
and the c++ implementation of ArraySize
:
int ArraySize(boost::shared_ptr<LuaTable> T) { if (!T) return 0; return std::count_if( T->begin(), T->end(), [](std::pair<LuaMultiValue,LuaMultiValue> const& entry) { return GetType(entry.first) == LuaType::NUMBER; }); }