C
C#3w ago
Holipop

Porting a tiny library from Lua to C#

For context, I work with LOVE which is a game framework for Lua. One of the planned updates is API to allow people to make their own language bindings and C# is popular with making games so I figured, why not try and port a really tiny library over to C# just for fun, even if its not gonna be useful right now? (the lib in question, it's a scene manager and its just like 130 lines) https://github.com/tesselode/roomy/tree/master Here's my roadblock though: In Lua, using Roomy would look like this:
local manager = roomy.new()

local scene = {}
function scene.eventA (x, y)
print(x + y)
end
function scene.eventB (arr)
for i = 1, #arr do
print(arr[i])
end
end

manager.push(scene)
manager.emit("eventA", 2, 4) -- prints 6
manager.emit("eventB", { "foo", "bar", "egg" }) -- prints "foo", "bar", "egg"
local manager = roomy.new()

local scene = {}
function scene.eventA (x, y)
print(x + y)
end
function scene.eventB (arr)
for i = 1, #arr do
print(arr[i])
end
end

manager.push(scene)
manager.emit("eventA", 2, 4) -- prints 6
manager.emit("eventB", { "foo", "bar", "egg" }) -- prints "foo", "bar", "egg"
What I'd like is to replicate this same sort of behavior as close as possible, keeping Emit as a method that takes a name of an event and looks for it in a Scene, passing in the remaining parameters but I don't know how to ensure strong typing for different events. Just having object[] works but it'd mean every event would have to add type checking at the top of their definitions.
var manager = new Manager();
var scene = new Dictionary<string, Action>();

scene["eventA"] = (int x, int y) => {
Console.WriteLine(x + y);
}
scene["eventB"] = (string[] arr) => {
foreach (var str in arr) Console.WriteLine(str);
}

manager.Push(scene);
manager.Emit("eventA", 2, 4);
manager.Emit("eventB", new string[] { "foo", "bar", "egg" })
var manager = new Manager();
var scene = new Dictionary<string, Action>();

scene["eventA"] = (int x, int y) => {
Console.WriteLine(x + y);
}
scene["eventB"] = (string[] arr) => {
foreach (var str in arr) Console.WriteLine(str);
}

manager.Push(scene);
manager.Emit("eventA", 2, 4);
manager.Emit("eventB", new string[] { "foo", "bar", "egg" })
Hope that explains enough, I might be missing some details
1 Reply
Holipop
Holipop3w ago
Alternative question: is what I want even worth it/possible?